#!/bin/sh
# getback [-o /backup] filename

PATH=/bin:/usr/bin:/usr/ucb; export PATH
BACKUP=/backup
myname=`basename $0`
TMP=/tmp/${myname}$$
USER=${USER-`whoami`} || exit

usage() {
	echo "Usage: $myname [-o /backup] filename" 1>&2
	exit 1
}
sorry() {
	echo "Sorry, there are no online backups of $filename"
	exit 1
}
giveup() {
	echo "$myname: nothing changed"
	exit 1
}

set -- `getopt o: $*`
if [ $? != 0 ]; then
	usage
fi
for i in $*; do
	case $i in
	-o) BACKUP=$2; shift 2;;
	--) shift; break;;
	esac
done

if [ $# != 1 ]; then
	echo "$myname: missing filename" 1>&2
	usage
fi

filename=$1
case $filename in
/*) backdir=$BACKUP$1;;
*)  backdir=$BACKUP`/bin/pwd`/$1;;
esac

test -d $backdir || sorry
trap "/bin/rm -f $TMP; exit" 0 1 2 15
# We could ensure that the backup filenames look reasonable here...
ls -lrt $backdir | awk "\$1 ~ /^-/ && \$3 == \"$USER\"" >$TMP
ncopies=`sed -n '$=' $TMP`
case $ncopies in
1)
	set -- `cat $TMP`
	echo "There is only one backup of \"$filename\", dated $5 $6 $7"
	echo -n "Retrieve this copy [y] ? "
	read ans
	case "$ans" in
	"" | y* | Y* ) ;;
	*) giveup;;
	esac
	;;
[0-9]*)
	echo "There are $ncopies backup versions of \"$filename\" from:"
	echo ""
	awk '{printf "\t%2d.\t%s %2d %s\t(%d bytes)\n", NR,$5,$6,$7,$4}' $TMP
	echo ""
	while :; do
		echo -n "Enter number corresponding to the version you want [$ncopies] "
		read ans
		case "$ans" in
		"")
			version=$ncopies
			break;;
		n* | N*)
			giveup;;
		[0-9]*)
			if [ $ans -gt 0 -a $ans -le $ncopies ]; then
				version=$ans
				break
			fi;;
		esac
		echo "Answer must be a number from 1 to $ncopies, or <cr>."
	done
	set -- `sed -n ${version}p $TMP`
	;;
*)
	sorry;;
esac
if [ -f $filename ]; then
	owner=`ls -l $filename | awk '{print $3}'`
	if [ $owner != $USER ]; then
		echo "$myname: you are not the owner of $filename"
		exit 1
	fi
	echo -n "\"$filename\" exists, overwrite [y] ? "
	read ans
	case "$ans" in
	"" | y* | Y* );;
	*) giveup;;
	esac
fi
echo -n "Retrieving $5 $6 $7 version of \"$filename\" ... "
cp -p $backdir/$8 $filename || {
	echo $myname: copy failed
	exit 1
}
# Update the times, but keep the modes
touch -f $filename || echo $myname: Can\'t touch \"$filename\"
echo "done!"
exit 0
