#!/bin/ksh -p
# Version 2.51
# The talk command tends to interrupt people in the middle of a shell
# based program (like pine or elm). Talk2 abolishes this and tells the
# user if their party is doing something else. 
# Spots if party is already talking to them.
# Version history:
# 	v1.xx - talk2, basic script
#	v2.0b - "Mail if not present" option
#       v2.5b - Re-written in stabler ksh
#	v2.51 - most of the bugs worked out
set -x
USER=$(whoami)

usage()
{
  echo "Usage: $progname [-m] username" 
  exit 1
}

mailem()
{
  print -n "[A]utomail or [C]ancel?: "
  read yn
  if [ $yn == "a" ] || [ $yn == "A" ] ; then
    mailf="User $USER ${progname}ed you today at $( date '+%H:%M' )"
    mailf="$mailf but you were unavailable"
    echo $mailf | mailx -s "${progname}: Notice" $party
    echo "Message sent to ${party}."
  fi
  exit 0
}

progname=$( basename ${0} )
set -A argv -- $@
mailf=0

if (( ${#argv[*]} < 1 || ${#argv[*]} > 2 )) ; then usage ; fi

if [[ "${argv[0]}" == '-m' ]] ; then
  mailf=1
  argv[0]=${argv[1]}
  unset argv[1]
fi

if (( ${#argv[*]} != 1 )) ; then usage ; fi

party=${argv[0]}

pts=$( echo ${argv[*]} | grep -c "$USER" )

if (( $pts != 0 )) ; then
  echo "They'll lock you up for that! :)"
  exit 1
fi

here=$( expr "$party" : ".*@" )

# just in case they're not on this server...
if (( $here != 0 )) ; then
 talk $party
 exit 0
fi

set "$( \w | grep '^'$party )"

if (( $# < 2 )) ; then
  echo "User $party is not logged on."
  if (( $mailf == 1 )) ; then mailem ; fi
  exit 2
fi

set -A pts $( \w | grep "^$party" | grep "talk" | grep "$USER" )

if (( ${#pts[*]} < 2 )) ; then
  set -A pts $( \w | grep "^$party" | grep 'sh$' )
fi

set -A k $( \w -s | grep "^$party" | awk '{FS = ""}{print substr ( $1, 30 )}' )

if (( ${#pts[*]} < 2 )) ; then
  echo "User $1 is running ${k[0]}."
  if (( $mailf == 1 )) ; then mailem ; fi
  exit 2
fi

pts=${pts[1]}

talk $party $pts
exit 0
