#!/bin/csh -f

#
# Empalarm -- Check an empire game to see if we were attacked
#
# Usage: empalarm <Country> <Password> <login to mail to> <Host> <Port>
#
# Empalarm is meant to be run as a cron job, or an at script.
#

# Set this directory to the location of the empire binary
set BINDIR=/home/chainsaw4/ts/bin

# Set this directory to the location of the attacked awk script
set AWKDIR=/home/chainsaw4/ts/E

# Set this to a file that empalarm can use to make sure
# that it only sends you mail once. You need to remove
# this file before empalarm will work again. To do this,
# call empalarm with no arguments.

set LOCKFILE=/home/chainsaw4/ts/.empalarm_lock

if ( "$#argv" == "0") then
	echo Removing old lock file $LOCKFILE...
	rm -f $LOCKFILE
	exit 1
endif

if ( "$#argv" != "5" ) then
	exit 1
endif

setenv EMPIREHOST $4
setenv EMPIREPORT $5

$BINDIR/empire $1 $2 > /tmp/empalarm$$ << !
read 0 n
quit
!

# check and see if we were attacked
set a=`awk -f $AWKDIR/attacked.awk < /tmp/empalarm$$`

set mailme=0

if ( "$a" != "" ) then
	set mailme=1
endif
if ( "$mailme" == "1" ) then
	if (-r $LOCKFILE ) then
#
# We've already sent an alarm. Don't bother.
#
		exit 1
	else
		mail $3 << !
HELP! We're under attack in the game at $4, port $5!
.
!
#
# Save the sectors attack in the lockfile.
#
		echo $a > $LOCKFILE
	endif
endif
