#!/bin/bash

# Use nano as a writing environment.  This script is specific to Linux
# and xfce4 although it could be adapted for terms used in other
# window managers/desktop environments.  It is a simple wrapper to
# nano that provides a few conveniences.

# Put the script somewhere in the command path.  Create a "nanopath"
# directory and edit the variable below.  No blanks or special
# characters, please.

nanopath="$HOME/data/nano"

# Usage:

#   nanowrite <optional filename>

# where 'filename' must be in the 'nanopath' directory. It can be a
# new file.  No blanks or special characters in the filename, please.
# If no file name given, try to open most recently used file in the
# nanopath directory, ignoring files that start with a dot like
# .mylittlescript or the like.

# You might want to use a wrapper along lines like this:

#  xfce4-terminal --zoom=2 --color-bg="Black" --color-text="Lawn Green" --geometry=64x20 -e "nanowrite $1"

# Note that the nano window may not behave correctly if this script is
# launched from inside emacs or from some environment that doesn't
# provide the right information about a containing term.

# This is not yet another "distraction free" writing tool.  Writing
# takes place in a relatively small window.  This is deliberate.  The
# idea was to create a fast and useful tool using stock Linux
# utilities and the very fast and very capable nano editor.  It is not
# intended as a substitute for the more complex and featureful writing
# environments that can be created in something like Emacs.

# Of course, it just seemed fitting that if you participate in
# NaNoWriMo (nanowrimo.org), you might use--- nano.

# You need to do version control on your own, but RCS is a venerable
# tool for single file, single user text file versioning.

# Some extremely rudimentary word count facilities are provided.  A
# file named .nanolog is kept in the nano path directory which shows
# directory word count out, directory word count in, change in word
# count, clock-out date, clock-out time, clock-in date, clock-in time,
# and elapsed minutes (rounded down but never less than 1).  The stats
# file is in comma separated values (CSV) form.

# Note this is a count of all words in the nanopath directory and not
# a word count of the file you may have requested on the command line.
# This is because nano is in multibuffer mode (for better utility) and
# you might have changed more than one file.

# Of course there are issues with this.  If you delete stuff, that
# counts as a negative on your word count (although the stats file
# will never record less than 0 words per session).  It's best to do
# any significant deletions outside of nanowrite.

# You can process the .nanolog any way you wish, such as with gnuplot
# or R or anything else.  I could have put more stuff into .nanolog
# but that might just load it with unhelpful data.  You can compute
# anything you wish with an offline script.

# Hint: If you create any auxiliary files in your nanopath directory
# name them with a '.'  at the start to avoid having one appear to be
# the most recently modified file, and to avoid having it included in
# the word count.

# Released into the public domain, Bob Newell, Honolulu, Hawai`i,
# January 2023.  No support provided and no warranties given.  Comments
# to bobnewell@bobnewell.net but I make no promises!

nanologfile="$nanopath/.nanolog"

# You can change these options to suit if you are familiar with nano's
# options.  I chose a set that I find most useful and convenient for
# writing.
options="-jSakPHF0MU -f $nanopath/.nanorc -o $nanopath"

cd "$nanopath"

if [[ $1 == "" ]]
# We don't have a file on the command line so look for the most
# recently modified file in the nanopath directory.
then
	lastfiledate=0
	usethisfile=""
	for nanofile in *;
	do
	    if [[ -f "$nanofile" ]]
	    then
		thistime=`stat -c %Y "$nanofile"`
		if [[ $thistime -gt $lastfiledate ]]
		then
		    lastfiledate=$thistime
		    usethisfile="$nanofile"
		fi
	    fi
	done
else
# There IS a file on the command line. We select the requested file
# (which may be a new file) without checking to be sure it exists (or
# will exist) in nanopath.  This is up to the user to deal with, as
# there are too many possible variants to check.
	usethisfile="$1"
fi

# Clock in with date, time, word count (if any).
wordsin=`wc -w * | tail -1`
wordsin=`echo $wordsin|awk '{print $1}'`
datein=`date +"%Y-%m-%d %T"`

# Not sure if this is a good idea but try to prevent disaster,
# including loss of word count.
trap "" QUIT
trap "" INT
trap "" HUP
trap "" TSTP

# Finally launch nano.
nano $options $usethisfile

# Now close out by computing final stats, and writing to log file.
wordsout=`wc -w * | tail -1`
wordsout=`echo $wordsout|awk '{print $1}'`

deltawords=$(($wordsout - $wordsin))
if [[ $deltawords -lt 0 ]]
then
    deltawords=0
fi

dateout=`date +"%Y-%m-%d %T"`

dateinsec=`date --date "$datein" +%s`
dateoutsec=`date --date "$dateout" +%s`
minutes=$(( ($dateoutsec-$dateinsec)/60 ))

if [[ minutes -le 0 ]]
then
    minutes=1
fi

# Now break up day/time.
dod=`echo $dateout|awk '{print $1}'`
dot=`echo $dateout|awk '{print $2}'`
did=`echo $datein|awk '{print $1}'`
dit=`echo $datein|awk '{print $2}'
`
# Write the stats to the end of nanologfile.
echo "$deltawords,$dod,$dot,$did,$dit,$minutes" >> "$nanologfile"

# Mini-report.
echo "$deltawords words written in $minutes minutes."

exit 0
