#!/bin/sh
#
# td: TODO checking/maintainance utility
#
# Copyright (C) 1997 Mark Rigby-Jones
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# If you do not have a copy of the GNU General Public License then
# you can get one by writing to the Free Software Foundation, Inc.,
# 675 Mass Ave, Cambridge, MA 02139, USA.
#

version="td v1.1 by Mark Rigby-Jones, 17th Jan 1997"

todofile="/var/admin/TODO"
filedir="$HOME/.lg"
tmpfile="/tmp/td.$$"
pager="less -eis"
editor="pico"

if (test $EUID = 0); then
  echo "td: cannot be run as root - please return to your normal uid!"
  exit 1
fi

if !(test -d $filedir); then
  mkdir $filedir
fi

case "$1" in
  -e|--edit|-p|--page)
    if (test $# = 2); then
      todofile="$2"
    fi
    ;;
  -h|--help)
    cat << 'EOT'
Usage: td [function] [logfile]
Check whether a TODO file (/var/admin/TODO by default) has been changed, and
print a brief message if it has since last read using td. Other functions
shown below. Note that for security reason, you should not run td whilst
root - it will exit with an error message.

-e, --edit      edit the TODO file - locks the file from other td users and
                 allows you to edit it to your heart's content.
-p, --page      view the entire TODO file using a pager
-h, --help      print this information and exit
-V, --version   print version information and exit

If you need more info, then read the man page!
EOT
    exit 0
    ;;
  -V|--version)
    echo $version
    exit 0
    ;;
  *)
    if (test $# = 1); then
      todofile="$1"
    fi
    ;;
esac

if (test -e $todofile); then
  echo $todofile > $tmpfile
  dotsub=`tr / . < $tmpfile`
  chkfile="$filedir/$dotsub"
  rm $tmpfile
else
  echo "td: $todofile not found / illegal option"
  echo "try \`td --help' for more information"
  exit 1
fi

case "$1" in
  -e|--edit)
    if (test -n "$EDITOR"); then
      editor=$EDITOR
    fi
    if (test -n "$VISUAL"); then
      editor=$VISUAL
    fi
    lockfile="/tmp/td.$dotsub.lock"
    if (test -e $lockfile); then
      echo "td: $todofile is currently being edited - try again later"
      exit 1
    else
      touch $lockfile
      $editor $todofile
      touch $chkfile
      rm $lockfile
    fi
    ;;
  -p|--page)
    if (test -n "$PAGER"); then
      pager=$PAGER
    fi
    touch $chkfile
    $pager $todofile
    ;;
  *)
    if !(test -e $chkfile && test $chkfile -nt $todofile); then
      echo "$todofile has been modified"
    fi
    ;;
esac
