#!/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/_ldap_local_
  exit $1
}

copyldap()
{
   FEXT=$RANDOM
   if [ -f /etc/ssl/certs/hmcldapcert.pem ]; then
      cp -p /etc/ssl/certs/hmcldapcert.pem /etc/ssl/certs/hmcldapcert.pem.$FEXT
   fi
   if [ -f $1 ]; then
     mv $1 /etc/ssl/certs/hmcldapcert.pem
     if [ $? -eq 0 ]; then
       chown root.root /etc/ssl/certs/hmcldapcert.pem
       chmod 400 /etc/ssl/certs/hmcldapcert.pem
     else
       if [ -f /etc/ssl/certs/hmcldapcert.pem.$FEXT ]; then
          mv /etc/ssl/certs/hmcldapcert.pem.$FEXT /etc/ssl/certs/hmcldapcert.pem
       fi 
       exit_cleanup 6
     fi
   else
     if [ -f /etc/ssl/certs/hmcldapcert.pem.$FEXT ]; then
          mv /etc/ssl/certs/hmcldapcert.pem.$FEXT /etc/ssl/certs/hmcldapcert.pem
     fi 
     exit_cleanup 6
   fi
}

#-------------------------------------------------------------------------------
# "Main" program start   
#-------------------------------------------------------------------------------
# Check usage error
if [ "$1" = "" ]; then
   echo "Usage: getRemoteFile <file> [ <ftp server> ] [ <user> ] [ <password> ]"
   exit_cleanup 1
fi
CAFILE=$1
SERVER=$2
USER=$3
PASSWD=$4
CAFILENAME=`/usr/bin/basename $CAFILE`

# Ldap must already be configured. If not, error.
/usr/bin/egrep -q _hmc_cookie /etc/openldap/ldap.conf
if [ 0 -ne $? ]; then
      exit 7
fi

# Server not specified, if file exists locally copy it
if [ "$SERVER" = "" ]; then
   if [ ! -f $CAFILE ]; then
      exit 6
   else
      copyldap $CAFILE
   fi
else
   # Check connectivity
   /bin/ping -c 2 $SERVER >/dev/null 2>&1
   if [ $? -ne 0 ]; then
      /bin/ping6 -c 2 $SERVER >/dev/null 2>&1
      if [ $? -ne 0 ]; then
         exit_cleanup 4
      fi
   fi
#-------------------------------------------------------------------------------
# 'sftpGetFile' the file from service server
#-------------------------------------------------------------------------------
   mkdir -p /tmp/_ldap_local_
   rm -f /tmp/_ldap_local_/*
   /opt/hsc/bin/sftpGetFile $SERVER $CAFILE $USER $PASSWD "/tmp/_ldap_local_"
   rc=$?
   if [ $rc -eq 0 ]; then
      if [ -f /tmp/_ldap_local_/$CAFILENAME ]; then
         copyldap /tmp/_ldap_local_/$CAFILENAME
      else
	 exit_cleanup 6
      fi
   fi
fi
exit_cleanup $rc
