#!/bin/bash
#
#-------------------------------------------------------------------------------
# FTPs files from the HMC efix ftp server
#
# 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 - 'ftp' connection error
# 5 - "other" 'ftp' error
# 6 - target file not written to HMC
#
#-------------------------------------------------------------------------------
#

function exit_cleanup {
#   rm -f $FTP_LOG_FILE
   chmod 777 $FTP_LOG_FILE
   exit $1
}

function ftpRemoteFiles {
   FTP_SERVER=$1
   REMOTE_FILE=$2
   REMOTE_DIR=`/usr/bin/dirname ${REMOTE_FILE}`
   FILE=`basename ${REMOTE_FILE}`
   USER=$3
   PASS=$4
   cat << END_CLIENT_FTP | $FTP_CMD -vn $FTP_SERVER 2>&1 > $FTP_LOG_FILE
user $USER $PASS
bin
cd $REMOTE_DIR
get $FILE /var/adm/invscout/microcode/$FILE
quit
END_CLIENT_FTP
} # end function getRemoteFiles

#-------------------------------------------------------------------------------
# "Main" program start   
#-------------------------------------------------------------------------------
FTP_LOG_FILE=/var/hsc/log/remoteFirmwareFile.log
FTP_CMD=/usr/kerberos/bin/ftp

if [ "$1" = "" ]
then
   echo "Usage: getRemoteFirmwareFile <ftp server> <remote file> <user> <password>"
   exit_cleanup 1
fi

#-------------------------------------------------------------------------------
# 'ftp' the file from service server
#-------------------------------------------------------------------------------

# Just in case we have NLS troubles comparing system cmd outputs...
LANG=en_US
export LANG

# wipe out any prior file
if [ -f /var/adm/invscout/microcode/$2 ]
then
   rm -f /var/adm/invscout/microcode/$2
fi

# ftp the new file
ftpRemoteFiles $1 $2 $3 $4

# transfer complete(?) -> see if the file actually got written to the HMC
if [ -f /var/adm/invscout/microcode/$FILE ]
then
   chmod 555 /var/adm/invscout/microcode/$FILE
   exit_cleanup 0
else
   # look for "Transfer complete", "Successful transfer" or equivalent msg code
   # careful on grep'ing for all these values - note the space
   grep -i "^226 " $FTP_LOG_FILE 2>&1 >/dev/null
   if [ $? -ne 0 ]
   then
     # ftp failed for some reason - find out why
     grep -i "^230 " $FTP_LOG_FILE 2>&1 >/dev/null
     if [ $? -ne 0 ]
     then
        exit_cleanup 2
     fi
   
     grep -i "^550 " $FTP_LOG_FILE 2>&1 >/dev/null
     if [ $? -eq 0 ]
     then
        exit_cleanup 3
     fi
   
     errRC=$(grep -i "Not connected" $FTP_LOG_FILE)
     if [ -n "$errRC" ]
     then
        exit_cleanup 4
     else
        # none of the above errors
        exit_cleanup 5
     fi
   else
      exit_cleanup 6
   fi
fi
exit_cleanup 0
