#! /bin/sh

# This script is responsible for providing processing
# that follows a restore of critical console data on the HMC
# This scripts runs right after the data has been restored during
# boot and prior to reboot the HMC


# Handle kernel updates which result in kernel files
# such as bzImage, SystemMap etc.. being included in the
# critical console data backup. The net result is, we
# will have more than 1 set of kernel images.
# If there are kernel images backed up, the backup process
# will create a file /boot/new_hmc_kernel and made it part
# of the backup. As soon as this file is restored, it will signal
# that some cleanup need to be done.

if [ -f /boot/new_hmc_kernel ]; then
      # Some checking before proceeding
      kname=`cat /boot/new_hmc_kernel`
      kversion=`echo $kname | cut -c9-`
      if [ $kname = "" ]; then
         exit 0
      fi
      if [ ! -f /boot/$kname ]; then
         exit 0
      fi
      echo "New kernel restored from critical console data."
      echo "Switching to new kernel..."
      mount -n -o remount,rw /
      mkdir -p /boot/SAVED
      cp -p /boot/*$kversion* /boot/SAVED/
      rm /boot/bzImage-*
      rm /boot/Kerntypes-*
      rm /boot/symvers-hmc_mcp*
      rm /boot/System.map-*
      rm /boot/vmlinux-*
      mv /boot/SAVED/* /boot/
      rm -rf /boot/SAVED
      ln -sf /boot/bzImage-* /boot/bzImage
      rm -f /boot/new_hmc_kernel
      sleep 2
      sync
fi

#
# Special case here - the 'hwscand' program may be executing prior to the boot.init
# (i.e., restore script invocation) and a subsequent un-tar of that program - if it
# was in the archive file results in a non-zero tar exit code. Coordinating with
# the backup script, detect the if the *copy* of the this potentially backed'd up
# file was in the archive and post-process here. See defect 624653
#
if [ -f /opt/hsc/data/backup/stage/hwscand.orig ]; then
    # copy of program was successfully unpacked...
    # see if service needs to be halted

    # First determine if portmap is running - it should not be.
    # Then start that service for the duration of this script
    HWSCAND=/usr/sbin/hwscand
    HWSCAND_SHORT=hwscand
    PID=`ps -ef | grep $HWSCAND_SHORT | grep -v grep | awk '{print $2}'`

    # if program is executing, stop it
    if test -n "$PID" ; then
#        echo "hwscand is currently executing, PID is $PID." >> $LOG
        kill -9 $PID
    fi

    # rename the copy of the original file back to it's original name and restart
    # if it was determined to be previously executing
    mv /opt/hsc/data/backup/stage/hwscand.orig %HWSCAND
    if test -n "$PID" ; then
        HWSCAND &
    fi
fi
exit 0
