#! /bin/sh
CPU=`cat /etc/cputype`
PATH=/u/dump/bin:/u/dump/etc.$CPU:/usr/ucb:/bin:/usr/bin:/etc:/usr/etc

TAPE=${TAPE:-/dev/nrrt0}; export TAPE


set -e
trap "echo $0: aborting at "'`date` >&2; exit 1' 0

gettoc -r

set -- `wc -l <toc`
NF=$1
TOCHEAD="`head -1 toc`"
set -- $TOCHEAD
echo "Tape is $4 --" $NF "files holding `sofar toc`."
echo -n "Display contents [n] ? "; read yn
case "$yn" in [yY]*) cat -n toc ;; esac

# Weekday-specific stuff
FS5="/ /usr.MC68020 /pub.MC68020 /usr1 /usr2 /usr4"
FS3="$FS5 riemann:/ riemann:/usr klein:/ quasifuchs:/ schottky:/ schottky:/bootdisk/NeXT"
FS0="/ /usr.MC68020 /pub.MC68020 /usr1 /usr2 /usr4 klein:/ quasifuchs:/"
FSSpec="/usr5 /usr6 riemann:/ riemann:/usr klein:/ quasifuchs:/ schottky:/ schottky:/bootdisk/NeXT"

case "$NF#`date +%w`" in
  1#*)	level=0; ;;	# Level 0 dumps at start of each tape (?)
  *#1)	level=3; ;;	# Monday Level 3 dumps
  *)	level=5; ;;	# Daily level 5 dumps
esac

echo -n "Dump level (0, 3, 5, S(pecial)) [$level] ? "; read lev
case "$lev" in
  [0-9]) level=$lev ;;
  [nNqQ]*) exit 1 ;;
  ""|[yY]*) ;;
  [sS]*) level=S ;;
  *) echo "Wanted a dump level digit, using $level" ;;
esac

case $level in
  0) FS="$FS0" ;;
  [123]) FS="$FS3" ;;
  [4-9]) FS="$FS5" ;;
  S) FS="$FSSpec" ; level=0 ;;
esac

echo "Will dump:
`echo $FS | tr '\40\11' '\12\12' | sed -e 's/^/	/'`
at dump level $level.  Writing dump script to ./script."
echo -n "Schedule dump [n] ? "; read dosched

OIFS="$IFS"
CIFS=":$IFS"

rm -f script
exec >script
chmod 755 script
echo \
"#! /bin/sh
exec >script.log 2>&1
set -x
date
PATH=$PATH
TAPE=$TAPE
trap 'echo Tape error or wrong tape in drive, exiting;
	rm -f script.running;
	date
	Mail -s Dump-failed dump <script.log
	exit 1' 0
set -e
> script.running
gettoc -a
"'tochead="`head -1 toc`"
trap "rm -f script.running;
	date;
	Mail -s Dump-failed dump <script.log;
	exit 1" 0
if [ "$tochead" != "'"$TOCHEAD"'" ]; then
	echo Wrong tape in drive: expected "'"$TOCHEAD"',"
	echo found "$tochead".  Exiting.
	exit 1
fi
'

# Now back to our sponsor.. the following writes the bulk of "script".
for fs in $FS
do
    IFS="$CIFS"
    set -- $fs
    IFS="$OIFS"
    case "$1" in
    riemann)
	# Simulated dump levels with "tar" dates
	# We should really have a "tardates" file like /etc/dumpdates
	# and search it with a date-interpreting program but who cares.
	since=`date "+%y %m %d $level" |
	 awk '{ level=$4;
		if(level == 0) exit;
		if (level == 3) days=8; else days=2;
		$3 -= days;
		if($3 <= 0) { $2--; $3 += 28; if($2 <= 0) { $2=12; $1-- } }
		printf "-N %02d.%02d.%02d.00.00", $1, $2, $3;
	     }' `

	echo remotetar -G $since $1 $2
	;;
    /*)
	echo localdump ${level}u $1
	;;
    *)
	echo remotedump $1 ${level}u $2
	;;
    esac
done

echo 'trap "rm -f script.running" 0'

case "$dosched" in
  [yY]*) at -s 4a ./script ;;
esac
trap "" 0
