#!/bin/bash
#
#-------------------------------------------------------------------------------
# FTPs file from the HMC to a remote system
#
# 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 ftpRemoteFiles {
   BASE_FILENAME=`/usr/bin/basename $1`
   FILE=$1
   FTP_SERVER=$2
   REMOTE_DIR=$3
   USER=$4
   PASS=$5
   cat << END_CLIENT_FTP | $FTP_CMD -vn $FTP_SERVER 2>/dev/null > $FTP_LOG_FILE
user $USER $PASS
bin
put $FILE $REMOTE_DIR/$BASE_FILENAME
quit
END_CLIENT_FTP
} # end function ftpRemoteFiles

function sftpRemoteFiles {
   FILE=$1
   FTP_SERVER=$2
   REMOTE_DIR=$3
   USER=$4
   IDFILE=$5
   if [ "$IDFILE" != "" ]
   then
      idarg="-o IdentityFile=$IDFILE"
   fi
   echo "put $FILE" > $SFTP_CMD_FILE
   $FTP_CMD -b $SFTP_CMD_FILE -o StrictHostKeyChecking=no $idarg $USER@$FTP_SERVER:$REMOTE_DIR >/dev/null 2>&1
   return $?
} # end function ftpRemoteFiles
exit_cleanup()
{
  rm -f $SFTP_CMD_FILE 2>/dev/null
  exit $1
}

#-------------------------------------------------------------------------------
# "Main" program start   
#-------------------------------------------------------------------------------
FTP_LOG_FILE=/var/hsc/log/ftp.log
SFTP_CMD_FILE="/tmp/remote_ftp.$RANDOM"
if [ "$1" = "" ]
then
   echo "Usage: putRemoteFile <file> <ftp server> <remote dir> <user> { <password> | <key file> } <mode>"
   exit_cleanup 1
fi
#-------------------------------------------------------------------------------
# 'ftp' the file from service server
#-------------------------------------------------------------------------------
if [ "$6" == "sftp" ]
then
   FTP_CMD=/usr/bin/sftp
   sftpRemoteFiles $1 $2 $3 $4 $5
   exit_cleanup $?
else
   FTP_CMD=/usr/kerberos/bin/ftp
   ftpRemoteFiles $1 $2 $3 $4 $5
   # 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 >/dev/null 2>&1
   if [ $? -ne 0 ]
   then
     # ftp failed for some reason - find out why
     # special case for i5 OS FTP
     grep -i "^250 " $FTP_LOG_FILE 2>&1 >/dev/null
     if [ $? -eq 0 ]
     then
	exit_cleanup 0
     fi

     grep -i "Not connected" $FTP_LOG_FILE >/dev/null 2>&1
     if [ $? -eq 0 ]
     then
        exit_cleanup 4
     fi
     grep -i "^230 " $FTP_LOG_FILE >/dev/null 2>&1
     if [ $? -ne 0 ]
     then
        exit_cleanup 2
     fi
     exit_cleanup 5
  fi
fi
exit_cleanup 0
