#!/bin/csh -f

# This command updates the .plan file to show last login or last
# logout, for example.
# The first argument, $1, is the key by which the line to be updated is
# recognized.  The first line beginning "Last $1" will be updated.
# The second argument, $2, is additional text to be inserted into the
# line, i.e., the line will show "Last $1$2:	" followed by the current time
# and the machine where the command is run.

# You might want to put in your .login
#    planupdate "login"
# and put in your .logout
#    planupdate "logout"
# Or if you want only the most recent of the two to appear in your .plan,
# you could use
#    planupdate "in|out" " (login)"
# in your .login, and
#    planupdate "in|out" " (logout)"
# in your .logout.
# Also, for people who frequently work on a remote machine while idling on
# the one they have logged in to, something like the following insertion to
# your .cshrc could be useful:
#    alias rsh 'planupdate rsh " (\!:1)"; \rsh \!:*'
# You also might be interested in having your rsh do something like this:
#    \rsh $1 planupdate \"rsh in\" \" \(from $HOSTNAME\)\"\; $argv[2-] &
# and installing planupdate in places you may rsh to.

# One last note.  It seems that you can stop this command from executing
# if you logout by modem and hang up before the command has finished.
# Probably to be safe, you are best off using nohup and & in your .logout,
# e.g.,
#    nohup planupdate seen " (logout)" &
# You could put it in the background in other invocations, too (e.g. in
# the .login), but you could get screwed up if you run the command multiple
# times concurrently, so I recommend using nohup and & just in the .logout
# unless you are slightly careful about what you are doing.

onintr -

if ($#argv == 0 || $#argv > 2) then
  echo 'Usage: planupdate key [comment]'
  exit(1)
endif

set tempfile = /tmp/planupdate.$USER.$$
awk 'BEGIN {found = "no"}\
     {output = $0}\
     /^Last\ '"$1"'.*/ {if (found=="no") {found = "yes";\
output = "Last '"$1""$2"':	'"`date`"' on '"`hostname`"'"}}\
     {print output}\
     END {if (found=="no") print "Last '"$1""$2"':	'"`date`"' on '"`hostname`"'"}'\
     ~/.plan > $tempfile
set result = $status
set wcplan = ( `wc ~/.plan` )
set wctemp = ( `wc $tempfile` )
if ($result || $wcplan[1]>$wctemp[1]) then
  echo "Error in updating plan (status $result).  Old .plan to be kept."
else
  cp $tempfile ~/.plan  # cp keeps the old protections of .plan unlike mv
  rm $tempfile
endif
