#! /bin/sh
#
#  - Stuart Levy, Geometry Group, April 1989
#
# remotedump  [-n]  hostname  {0-9}[u]  /filesystem-or-device
#
# -n    Don't write a table-of-contents file to the tape after the dump.
#
# {0-9}	Dump level - a single digit in the range 0..9.  Required.
# u	Update the /etc/dumpdates file on the remote machine.
#
# No other dump options are accepted.
#*
# One or two lines are added to the ./toc (tape table-of-contents) file:
# hostname  filesystem   level  yy.mm.dd.hh.mm  nbytes  "dump"  yy.mm.dd.hh.mm
# The first date is the present moment; the second is the date since which
# this dump was taken, if an incremental. 
# If a copy of the toc is written to tape another line is appended to toc:
# "Table" "of" "contents"  yy.mm.dd.hh.mm  nbytes  "toc"
#

notoc=
if [ "$1" = "-n" ]; then
	notoc=-n; shift
fi

case "$1#$2#$3#$4" in
    ?*#[0-9]#/*#|?*#[0-9]u#/*#)
	;;
    *)
	echo >&2 \
"Usage:  $0  [-n]   hostname   {0-9}[u]  /filesystem-or-device
Dump(8) specified filesystem on 'hostname' to tape given by TAPE envariable.
Digit 0..9 is dump level, optional 'u' => update /etc/dumpdates on remote host.
Writes a copy of the table-of-contents after the dump unless -n."
	exit 1
	;;
esac

if [ ! -w toc ]; then
	echo "$0: must have ./toc present and writable.  Run gettoc first." >&2
	exit 1
fi

CPU=`cat /etc/cputype`
PATH=/u/dump/bin:/u/dump/etc.$CPU:/usr/local/bin.$CPU:/usr/ucb:/usr/bsd:/bin:/usr/bin:/etc:/usr/etc
TAPE=${TAPE:-/dev/nrrt0}
BSIZE=${BSIZE:-64512}

DATE="`date +%y.%m.%d.%H.%M`"

# Security check - make sure we were invoked by "dump" or "root".
# Could leave this for slavedump to check but then we'd have already
# mucked with the tape.

case "`id`" in
    *dump*|*root*) ;;
    *) echo "$0 may only be invoked by user 'dump'.  Go away." >&2; exit 3 ;;
esac

host=$1
dumpopts=$2
fs=$3

TEMP=/tmp/buffer.$$
rm -f $TEMP $TEMP.2
TRASH="$TEMP $TEMP.2 $TEMP.3"

# Don't pipe rsh | maketoc here -- the rsh hangs if 'buffer' aborts in mid-run.

rsh $host -l dump -n \
	-O "buffer $BSIZE >$TAPE 2>$TEMP || echo buffer: exit "'$?'" >>$TEMP" \
	slavedump $dumpopts $fs  2>$TEMP.3 \
&& maketoc $fs $host <$TEMP.3 >$TEMP.2
s=$?

set --  "" `grep 'bytes copied' $TEMP`
if [ "$7" = "" -o "$7" = "0" ]; then
	echo buffer reported:
	cat $TEMP
	# If 'buffer' printed just one line, it probably really wrote an EOF.
	if [ `wc -l <$TEMP` = 1 ]; then
		echo $host $fs FAILED ${DATE} 0 dump >>./toc
	fi
	rm -f $TRASH
	exit 1
fi

cat $TEMP.2 >>./toc

if [ "$notoc" = "" ]; then
	cp ./toc $TEMP
	echo Table of contents `date +%y.%m.%d.%H.%M` $BSIZE toc >>$TEMP
	if dd if=./toc of=$TAPE bs=$BSIZE conv=sync; then
		cp $TEMP ./toc
	else
		echo $0: Error writing table-of-contents to $TAPE >&2
		rm -f $TRASH
		exit 1
	fi
fi
rm -f $TRASH
exit 0
