#!/bin/bash
#
#-------------------------------------------------------------------------------
# SFTPs file from a secure FTP server to the HMC using sftp
#
# Possible return codes are:
#
# 0 - no error
# 1 - usage error, invalid argument
# 2 - invalid userID/password combination
# 3 - source file not found on server
# 4 - 'sftp' connection error
# 5 - "other" 'sftp' error
# 6 - target file not written to HMC
#
#-------------------------------------------------------------------------------
#

exit_cleanup()
{
  rm -rf /tmp/_krb_local_
  exit $1
}

copykrb()
{
   FEXT=$RANDOM
   if [ -f /etc/krb5.keytab ]; then
      cp -p /etc/krb5.keytab /etc/krb5.keytab.$FEXT
   fi
   if [ -f $1 ]; then
     cp $1 /etc/krb5.keytab
     if [ $? -eq 0 ]; then
       chown root.root /etc/krb5.keytab
       chmod 400 /etc/krb5.keytab
       /opt/hsc/bin/KerberosSettings modify verify_ap_req_nofail true
       # in case of failure, copy saved file back
       if [ $? -ne 0 ]; then
	  if [ -f /etc/krb5.keytab.$FEXT ]; then
             mv /etc/krb5.keytab.$FEXT /etc/krb5.keytab
          else
             rm -f /etc/krb5.keytab
	  fi 
	  exit_cleanup 7
       else
	  rm -f /etc/krb5.keytab.$FEXT
          exit_cleanup 0
       fi
     else
       if [ -f /etc/krb5.keytab.$FEXT ]; then
          mv /etc/krb5.keytab.$FEXT /etc/krb5.keytab
       fi 
       exit_cleanup 6
     fi
   else
     if [ -f /etc/krb5.keytab.$FEXT ]; then
          mv /etc/krb5.keytab.$FEXT /etc/krb5.keytab
     fi 
     exit_cleanup 6
   fi
   rm -f $1
}

#-------------------------------------------------------------------------------
# "Main" program start   
#-------------------------------------------------------------------------------
# Check usage error
if [ "$1" = "" ]; then
   echo "Usage: getRemoteFile <file> [ <ftp server> ] [ <user> ] [ <password> ]"
   exit_cleanup 1
fi
KEYFILE=$1
SERVER=$2
USER=$3
PASSWD=$4
KEYFILENAME=`/usr/bin/basename $KEYFILE`
# Server not specified, if file exists locally copy it
if [ "$SERVER" = "" ]; then
   if [ ! -f $KEYFILE ]; then
      exit 6
   else
      copykrb $KEYFILE
   fi
else
   # Check connectivity
   /bin/ping -c 2 $SERVER >/dev/null 2>&1
   if [ $? -ne 0 ]; then
      exit_cleanup 4
   fi
#-------------------------------------------------------------------------------
# 'sftpGetFile' the file from service server
#-------------------------------------------------------------------------------
   mkdir -p /tmp/_krb_local_
   rm -f /tmp/_krb_local_/*
   /opt/hsc/bin/sftpGetFile $SERVER $KEYFILE $USER $PASSWD "/tmp/_krb_local_"
   rc=$?
   if [ $rc -eq 0 ]; then
      if [ -f /tmp/_krb_local_/$KEYFILENAME ]; then
         copykrb /tmp/_krb_local_/$KEYFILENAME
      else
	 exit_cleanup 6
      fi
   fi
fi
exit_cleanup $rc
