#!/bin/sh
#
#-------------------------------------------------------------------------------
#  backupHMCssh  <remote hostname>  <remote_dir> <filename>  <userid> <password> <mount> <operation>
#  $1 <remote hostname> target server 
#  $2 <remote_dir>      directory on target server
#  $3 <filename>        filename of the saved data
#  $4 <userid>          userid for ssh operation
#  $5 <password>        password for ssh operation
#  $6 <mount>           hda, hdc?
#  $7 <operation>       backup=1 | restore=2
#
# Possible return codes are:
#
# 0 - no error
# 31 - usage error, invalid argument
# 32 - invalid userID/password combination
# 33 - Failed to mount remote filesystem 
# 34 - ping of remote system failed 
# 35 - Cannot write to remote filesystem 
# 36 - tar command failed
# 37 - ssh command failed
# 38 - Failed to mount local filesystem 
#
#-------------------------------------------------------------------------------
#
#set -x

exit_cleanup(){
    cd /
    umount -l $DISKMOUNT/hmc/var
    umount -l $DISKMOUNT/hmc/dump
    umount -l $DISKMOUNT/hmc/extra
    umount -l $DISKMOUNT/hmc/mnt/upgrade
    umount -l $DISKMOUNT/hmc
    rm -rf $DISKMOUNT/hmc
    umount $DISKMOUNT
  
    umount /dev 
    umount $DEVMOUNT
    exit $1
}

MountBackupDir() {
    mkdir -p $DISKMOUNT/${1}
    mount -t ext3 /dev/${HD}${2} $DISKMOUNT/${1}
    if [ $? -ne 0 ]; then
        exit_cleanup 38;
    fi 
}

# main
DEVMOUNT="/backup/dev"
DISKMOUNT="/backup/disk"
REMOTEHOST=$1
REMOTEFILEDIR=$2
OUTFILENAME=$3
USERID=$4
PASSWD=$5
HD=$6
OP=$7

#debug
#echo  args in are $1 $2 $3 $4 $5 $6 $7

#need /dev for pty's. 
mount -t tmpfs /tmpdevfs $DEVMOUNT
cp -r /dev/* $DEVMOUNT
mount -t tmpfs /devtmpfs /dev
cp -r  $DEVMOUNT/* /dev


#create temp directory to mount the filesystems
# Because when we perform secure transfer we need
# to use ssh and expect and therefore needs to chroot
# into the full base image.
# On a restore, the disk partitions are mounted into the
# /hmc on RAM disk, as well as a temp mount point in
# /base1/backup/disk/. When restoring with ssh, the data
# is untar into the /base1/backup/disk/ root directory.

mount -t tmpfs /tmpfs $DISKMOUNT

cd $DISKMOUNT

# mount list of directories to backup
DIR_LIST="${HD}2 ${HD}3 ${HD}5 ${HD}7 ${HD}8"
echo "Mounting filesystems $DIR_LIST"

MountBackupDir hmc 2
MountBackupDir hmc/var 3
MountBackupDir hmc/hmc/mnt/upgrade 5
MountBackupDir hmc/dump 7
MountBackupDir hmc/extra 8

echo "Mounted filesystems."

#Call expect script
if [ "$OP" = "1" ]; then
    /opt/hsc/bin/send_ssh "$REMOTEHOST" "$REMOTEFILEDIR/$OUTFILENAME" "$USERID" "$PASSWD" 2>&1 
    if [ $? -ne 0 ] ; then exit_cleanup 37; fi 
fi

if [ "$OP" = "2" ]; then
    /opt/hsc/bin/recv_ssh "$REMOTEHOST" "$REMOTEFILEDIR/$OUTFILENAME" "$USERID" "$PASSWD" 2>&1
    if [ $? -ne 0 ] ; then exit_cleanup 37; fi 
fi

exit_cleanup 0

