#!/bin/bash
#
#-------------------------------------------------------------------------------
# Copies the microcode catalog file from CDROM to target location
#
# Possible return codes are:
#
# 0 - no error
# 1 - usage error, invalid argument
# 8 - cannot mount CDROM
# 9 - 'cp' command failed
# 6 - file does not exist on host system
#
#-------------------------------------------------------------------------------
#

# common exit point for script
exit_cleanup() {
    if [ $DO_UMOUNT -eq 0 ]; then
       echo "Skipping umount." >> $LOG
    else
       echo "Unmounting CDROM." >> $LOG
       umount /media/cdrom >>$LOG 2>&1
    fi   
    chmod 777 $LOG
    echo "Copy microcode files from CDROM log end." >> $LOG
    exit $1
}  

   
#-------------------------------------------------------------------------------
# "Main" program start   
#-------------------------------------------------------------------------------
LOG=/tmp/fileCD.log
FILENAME=$1
TARGET_DIR=$2
MOUNT_POINT=/media/cdrom
DO_UMOUNT=0

if [ "$1" = "" ]
then
   echo "Usage: getFileFromCDROM <filename> <target dir>"
   exit_cleanup 1
fi

# Start log to record actions
echo -e "Copy microcode catalog/files from CDROM log for `date`.\n" > $LOG

#-------------------------------------------------------------------------------
# simply copy the target file from CDROM to expected dircetory
#-------------------------------------------------------------------------------

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


# Mount the mirocode firmware CDROM at /media/cdrom.  Check first
# if media is already mounted - if so then unmount it
if grep "$MOUNT_POINT" /etc/mtab; then
   echo "CD ROM is already mounted, continuing..." >> $LOG
   DO_UMOUNT=0
else
   mount -v /dev/cdrom $MOUNT_POINT >> $LOG 2>&1
   if [ $? -ne 0 ]; then
      echo "The CD ROM cannot be mounted, error code = $?" >> $LOG
      exit_cleanup 8
   fi
   DO_UMOUNT=1
 
fi

# Now that the CDROM is mounted, copy the catalog file ($1) to the
# predetermined location (/var/adm/invscout/microcode)
cp $MOUNT_POINT/$FILENAME $TARGET_DIR >> $LOG 2>&1
if [ $? -ne 0 ]; then
   echo "The catalog file cannot be copied to target location, error code = $?" >> $LOG
   exit_cleanup 9
else
   # good transfer, now see if the file actually got written to the HMC
   echo "<$FILENAME> appeared to copy successfully, verifying..." >> $LOG
   x=`basename $FILENAME`
   if [ -f $TARGET_DIR/$x ]
   then
      chmod 777 $TARGET_DIR/$x
      echo "$FILENAME copied successfully." >> $LOG
      exit_cleanup 0
   else
      exit_cleanup 6
   fi
fi
exit_cleanup 0

