#!/bin/csh -f

# run empire commands automatically.  knows about btus and 
# not to to stomp on itself.

# there are three sections: 
#	1. get information
#	2. generate commands
#	3. run the commands

setenv EMPSHI .ashi		# ship file
setenv EMPCEN .acen		# census file

set CUT = 70			# don't run unless this many btus
set DIP = 10			# can go this many btu's under $CUT during run
set TO = "muir@postgres"	# send the results
set REPEAT_TIME = 6000		# sleep for this long between runs

#
# make sure you're in the right directory....
#

cd
cd e/play

#
# make sure you're not already running
#

if ($?EXECLOCK == 0) then
    echo locking auto
    setenv EXECLOCK
    exec execlock auto auto
    exit 0
endif

AGAIN:

#
# log a time stamp
#

date >.away_date

#
# disabled?
#

if (-f .noauto) exit


#
# check the btus
#

try_again:
set btu = `et < /dev/null | grep Command | sed 's/^\[[0-9]*:\([0-9]*\)\].*$/\1/p'`
if ($#btu != 2) then
	sleep 200
	goto try_again
endif

if ($btu[2] <= $CUT) then
	mail -s "no btus -- no automoves" $TO < /dev/null
	goto END
endif

any_way:

##########
#	get information
#########

rm -f .ashi .acen .axx .ant .acom .alev

echo 'cen #7 >.acen\
com #7 >.acom\
lev #7 >.alev\
ship >.ashi\
look r >.axx\
read >.ant\
y' | et >/dev/null

if (-e .ant) then

	##########
	#	generate commands
	##########

	cat .ant >>telegrams
	mail -s "telegrams ..." $TO < .ant
	goto END
	awk -f plague.awk plagued .ant > X ; mv X plagued
	awk -f terrorist.awk terrorist .acen .ant > X ; mv X terrorist
	awk -f milciv.awk .acen plagued terrorist >X ; mv X xlev
endif
goto END

if (-e .acen && -e .acom && -e .alev && -e .ashi ) then

	cat .axx >>.readlook
	rm -f .axx

	echo >do
#	./move >>do
	./manage -odoM .acen .acom .alev plagued xlev -P0,0 >>do

#	echo 'sel uw #7 977 .002' >>do
#	echo 'sel foo #7 9000 .00025' >>do
	echo 'sel lcm #7 1500 .025' >>do
	echo 'sel hcm #7 1000 .05' >>do
	echo 'sel i #7 800 .003' >>do
#	echo 'sel gun #7 300 .25' >>do
#	echo 'sel shel #7 2000 .11' >>do
	./drunk >>do

	##########
	#	run the commands
	##########


	#
	# check btu's again
	#

	try_again2:

	set btu = `et < /dev/null | grep Command | sed 's/^\[[0-9]*:\([0-9]*\)\].*$/\1/p'`
	if ($#btu != 2) then
		sleep 199
		goto try_again2
	endif

	@ useable = ( $btu[2] - $CUT ) + $DIP
	@ useable = $useable * 2

	set has = `wc -l < do`
	@ tossed = $has - $useable

	#
	# toss commands to get btu usage down
	#

	head -$useable do >dom

	#
	# run empire
	#

	( echo "tossing $tossed"; cat doM ; et < dom ) | mail -s "automoves" $TO
else
	mail -s "could not do auto (manage)" $TO < /dev/null
endif

END: 

##########
#	wait for a while
##########

sleep $REPEAT_TIME

goto AGAIN
