#!/bin/sh

PATH=/usr/ucb:/usr/bin:/bin:/usr/local/bin:/usr/sbin:/sbin

#
# run TCT from cron.  
# 
# Usage: /some/where/tct-cron tct-home [things to do]
#
# Default todo list: memory swap disk mactime grave-robber
#

# running grave-robber without writing the body file to disk.
TCT_NO_BODY_FLAGS="-i -P -s"

# Use remote storage for big things including the grave-robber body file, 
# to avoid thrashing memory/swap/disk more than necessary.
DESTHOST=192.168.1.1
DESTPORT=87
CRYPTKEY=secret

COMPRESS=gzip
ENCRYPT="bin/des -e -k $CRYPTKEY"
DELIVER="exp/tct-send $DESTHOST $DESTPORT"

DROP_COMMAND="$COMPRESS | $ENCRYPT | $DELIVER"

# Block hashing. Allow one hour per file system, 30+Gigs takes a while...
HASH_OPTS="-b 1024 -h 16"
RAM_HASH_OPTS="$HASH_OPTS"
SWAP_HASH_OPTS="$HASH_OPTS"
FS_HASH_OPTS="$HASH_OPTS -t 3600"

case $# in
 0) echo "Usage: $0 TCT-home-directory [things to do]"
    exit 1
    ;;
 1) TCT_HOME=$1
    set -- memory swap disk mactime grave-robber
    ;;
 *) TCT_HOME=$1
    shift
    ;;
esac

if test ! -d $TCT_HOME ; then
	echo "Directory $TCT_HOME not found, bailing out of $0 (2)"
	exit 2
	fi

# Time is used for naming the grave-robber storage, and for identifying data 
# that is dropped off remotely.

TIME=`perl -e "print time();"`;

if test $? -ne 0 -o -z "$TIME" ; then
	echo "Cannot figure results dir, bailing out of $0 (3)"
	exit 3
	fi

RESULT="graverob.$TIME"

cd $TCT_HOME

if test $? -ne 0 ; then
	echo "Cannot cd into $TCT_HOME, bailing out of $0 (4)"
	exit 4
	fi

rm -f *.log

# Collect the data in the specified order.
#
while :
do
    case $1 in

    memory)
	(echo "#! $TIME ramhash._dev_mem"; exp/ramhash $RAM_HASH_OPTS) | 
	    eval "$DROP_COMMAND" || {
		echo "ramhash failed, bailing out of $0 (6)"
		exit 6
	}
	;;


    swap)
	exp/swaphash $SWAP_HASH_OPTS -i $TIME -p "$DROP_COMMAND" || {
		echo "swaphash failed, bailing out of $0 (7)"
		exit 7
	}
	;;


    disk)
	exp/fshash $FS_HASH_OPTS -i $TIME -p "$DROP_COMMAND" || {
		echo "fshash failed, bailing out of $0 (8)"
		exit 8
	}
	;;
	

    mactime)
	(echo "#! $TIME body"; bin/grave-robber -m -b-) |
	    eval "$DROP_COMMAND" || {
		echo "Grave robber failed, bailing out of $0 (9)"
		exit 9
	}
	;;

    # grave-robber stores results in files that need to be shipped afterwards.
    grave-robber)
	bin/grave-robber -d $RESULT $TCT_NO_BODY_FLAGS || {
		echo "Grave robber failed, bailing out of $0 (10)"
		exit 10
	}
	(echo "#! $TIME $RESULT.tar"; tar cf - $RESULT) | 
	    eval "$DROP_COMMAND" && rm -rf $RESULT || {
		echo "Tar of results failed, bailing out of $0 (11)"
		exit 11
	}
	;;

    "")
	break
	;;

    *)
	echo "Unknown command: $1"
	exit 1
	;;
    esac
    shift
done

# Ship off the logs from grave-robber and other commands.
for log in *.log
do
    (echo "#! $TIME $log"; cat "$log") | eval "$DROP_COMMAND" &&
	rm -f "$log" || {
	    echo "Sending of $log failed, bailing out of $0 (12)"
	    exit 11
    }
done

# echo done
