#!/bin/ksh

###
# Run amrecover with options appropriate for this host.
###

###
# If we get an argument, assume it is a user name and change directory
# to the home file system for that user.
###

integer have_tapehost=0

while getopts :t:h c
do
   case $c in
   t) tapehost=$OPTARG
      integer have_tapehost=1
      ;;
   h) print -u2 "usage: ${0##*/} [-h] [-t tapehost] [user]"
      exit 0
      ;;
   \?)
      print -u2 "${0##*/}: unknown option: \"$OPTARG\""
      exit 1
      ;;
   esac
done
shift $((OPTIND - 1))

if (($# > 0))
then
   if [[ -n $1 ]]
   then
      cd ~$1/.. || exit 1
   fi
   shift
fi

host=$(hostname)
eval $(amlocal $host $1) || exit 1
if ((have_tapehost))
then
   amtapehost=$tapehost
fi

###
# Make sure we are at the top of a file system.
###

set -A df -- $(df -k . | sed 1d)
mount_point=${df[${#df[*]}-1]}			# get the rightmost field

if [[ ${df[0]} != /dev/* ]]
then
   print $PWD mounted from
   print ${df[0]}
   read "REPLY?Continue? "
   case $REPLY in
   y|yes)  ;;
   *)      exit 1
	   ;;
   esac
elif [[ $mount_point != $PWD ]]
then
   print $PWD mounted on
   print $mount_point
   read "REPLY?Continue? "
   case $REPLY in
   y|yes)  ;;
   *)      exit 1
	   ;;
   esac
fi

###
# Create a .bkrest.$$ area to do the work in.
###

(umask 077 ; ${DEBUG} mkdir .bkrest.$$) || exit 1
${DEBUG} cd .bkrest.$$ || exit 1

###
# Display some "useful" commands.
###

print "###"
fs=$(print $mount_point | sed s,/,_,g)
print "#cd /var/amanda/index/$amconfig/$host/$fs"
print "export TAPE=$amtapedev"
print "#ami $host $mount_point \$vsn \$TAPE $1 ; print '\\\\a\\\\c'"
print "#set -A jj -- \$(grep \"$host:$mount_point \" /var/amanda/$amconfig/\${vsn}_$amconfig.toc)"
print "#print \${jj[3]} KBytes: \$((\${jj[3]} / $amfactor / 60)) minutes"
print "#tpmount -f \$TAPE -v \$vsn ; print '\\\\a\\\\c'"
print "#mt fsf \${jj[0]?'jj not initialized'} ; print '\\\\a\\\\c'"
print "#tpunmount -f \$TAPE ; print '\\\\a\\\\c'"
print "###"

###
# Run amrecover.
###

${DEBUG} amrecover $amconfig \
	 -d $amtapedev \
	 -t $amtapehost \
	 -s $amindexhost

###
# Clear out the .bkrest.$$ area.
###

${DEBUG} cd $OLDPWD
read "REPLY?Clear out .bkrest.$$? "
case $REPLY in
y|yes)  ${DEBUG} rm -fr .bkrest.$$
	;;
*)      print -u2 "${0##*/}: .bkrest.$$ not removed"
	;;
esac

exit 0
