#!/bin/csh
# Version 2.0b
# 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.x - talk2, basic script
#	v2.0b - "Mail if not present" option

set progname = `basename $0`
@ mailf = 0

if ( $#argv < 1 || $#argv > 2) goto usage

if ("$1" == "-m") then
  @ mailf = 1
  shift
endif

if ($#argv != 1) goto usage 

@ pts = `echo $*|grep -c "$user"`

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

@ here = `expr "$1" : ".*@"`

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

set pts = ( `\w | grep "$1"` )

if ( $#pts < 2 ) then
  echo "User $1 is not logged on."
  if ($mailf == 1) goto mailem
  exit 2
endif

set pts = ( `\w | grep "^$1" | grep "talk" | grep "$user"` )

if ( $#pts < 2 ) set pts = ( `\w | grep "^$1" | grep 'sh$'` )

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

if ( $#pts < 2 ) then
  echo "User $1 is running $k[1]."
  if ($mailf == 1) goto mailem
  exit 2
endif

set pts = $pts[2]

talk $1 $pts
exit 0

usage:
  echo "Usage: $progname [-m] username" 
  exit 1

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