#!/bin/ash
# mu-atd : rustic atd, 
# (C) 1998 M. Andreoli
 
#set -x

SLEEP=30	# latency time
SPOOL=/var/spool/atspool; mkdir -p $SPOOL
LOGFILE=/var/log/atd.log
EXPR=expr
SED=sed


case "Z$1Z" in

Z-hZ|Z--helpZ)

cat << END

	at, atq, atrm - queue, examine or delete jobs for
	later execution -- mulinux rustic version.  

Usage: 
	at [DD] [HH:MM:SS]	# read command form stdin
				# [date form current month]
	atq 			# queue list
	atrm job		# remove "job" from list

Example:

	echo 'ppp-on' | at 18 22:30
END
exit
;;
esac


value()
{
AT=`echo "$@" | $SED "s/[A-z]//g" | $SED "s/19[0-9][0-9]//g"`

set -- $AT

d=0; h=0; m=0; s=0

for x in $1 $2
do


case "$x" in
*:* )
	set -- `echo $x | $SED s/:/\ /g`
	h=$1; m=$2; s=$3
	;;
*)
	d=$x
	;;
esac
done


md=`$EXPR 1440 \* $d`
mh=`$EXPR  60 \* $h`

r=`$EXPR $md + $mh`
r=`$EXPR $r + $m`
echo $r


}


process()
{
cmd=$1

now=`date`

batch=`value $AT`
current=`value $now` 

#echo "$cmd: $batch, now $current"

if [ "$batch" -le "$current" ] ; then
	echo "process $cmd at `date`" >> $LOGFILE 
	exec $cmd	# $cmd remove itself
fi


}

# wrapper

case "$0" in
*/at|at)  # add to queue

	# syntax

	[ $# = 0 ] && echo "argument error" && exit 
	# check if atd running

	if [ -z "`pidof atd`" ] ; then
		echo "Warning: atd daemon died?"
	fi

	echo "AT='$@'" > $SPOOL/$$
	echo "rm $SPOOL/$$" >> $SPOOL/$$
	cat >> $SPOOL/$$
	chmod +x $SPOOL/$$
	;; 
*/atq|atq) # queue list
	for b in `/bin/ls $SPOOL`
	do
	        read d < $SPOOL/$b
		eval $d
		echo "batch $b, at $AT"
	done
	exit
	;;
*/atrm|atrm) # remove form queue
	cd $SPOOL
	rm -f $@
	exit
	;;

*/atd|atd) # atd daemon

while [ 1 ]
do
for b in `ls $SPOOL` 
do
	read d < $SPOOL/$b
	eval $d
	process $SPOOL/$b
done

sleep $SLEEP
done
	;;
esac

