#!/bin/sh

# -------------------------------------------------------
# file   : install8k.sh
# purpose: Installation script to install hipath system.
#        : Provides unattended upgrades.
# author : Alex Rosa/Vittal.S/Koukoulas Nick
#
# usage  : install8k  [ -live ] [ -quiet ] [ -auto ]
#
# modifications:
# 05-19-12  Initial Creation .
# -------------------------------------------------------

ARGSLIST="$*"
LOGFILE=/log/prepare8k.log
INSTALL8KLOCKFILE=/lock/install8k.lock
CFG8k=/etc/hiq8000/node.cfg
REPOSITORY=/repository

# ----------------------------------------------------------
# function: logstr
# description:
#   logs string to logfile and stdout.
# ----------------------------------------------------------

logstr( )
{
   printf '%s\n' "$*"
   printf "[`date`]: install8k: %s\n" "$*" >>$LOGFILE 2>/dev/null
}

# -------------------------------------------------------
# function: getcfgvar
# args    : None
# description:
#   parses node.cfg for a specific parameter.
# -------------------------------------------------------

getcfgvar( )
{
   cfgfile=$1
   cfgarg=$2
   cfgvarres="`cat $cfgfile | grep -v '^#'| grep "$cfgarg[ ]*:"  \
                            | awk -F':' '{ print $2 }' | sed -e 's/[ \t]*//g'`"
   export $3="$cfgvarres"
} 2>/dev/null

#<InitializeErrorExitCode> \\OSV-11161
if [ -z "$Fail" ]; 
then
    Fail=1
fi
#</InitializeErrorExitCode>

if [ "$(id -u)" -ne 0 ]; then
   logstr "Cannot run without root permissions."
   exit $Fail
fi

#<ExitIfScriptIsAlreadyRunning> \\OSV-11351
# Check to see if install8k is running

if ! lockfile -r10 ${INSTALL8KLOCKFILE};
then
   logstr "install8k is already running"
   exit 2
fi
trap "rm -f ${INSTALL8KLOCKFILE}; exit" 0 1 2

while [ "$#" -gt "0" ];
do
   case $1 in
      -q)
         rpm -qi UNSPmigration 1>/dev/null 2>&1
         if [ $? -eq 0 ]; 
         then
            echo " status: success"
            rpm -q --queryformat 'version: %{NAME}-%{VERSION}-%{RELEASE}\n' UNSPmigration
         else
            echo " status: failed"
            echo "version: none"
         fi
         exit 0
         ;;
      -u)
         logstr "Toolkit update option selected."
         ;;
      -live)
         logstr "Will perform live upgrade."
         ;;
      *)
         ;;
   esac
   shift
done

# Check to see if upgrade8k is running
if [ -e /lock/syslock.upgrade ];
then
   logstr "upgrade8k is already running"
   exit 2
fi

if [ -e /repository/upgrade8k-timing ];
then 
   upgradestate=$(tail -1 /repository/upgrade8k-timing | awk '{ print $2 }')
   case "$upgradestate" in 
       "NoError"|"UpgradeReset"|"UpgradeResetCmd"|"")
	       :
	   ;;
       *)
	 xcount=$(grep -w "NoError\|UpgradeReset\|UpgradeResetCmd" /repository/upgrade8k-timing | wc -l)
	 if [ $xcount -eq 0 ]
	 then
	   logstr "upgrade8k is already running"
	   exit 2
	 fi
	   ;;
   esac
fi
#</ExitIfScriptIsAlreadyRunning>

#<CheckComposerFlag> \\OSV-10551
   echo "$ARGSLIST" | egrep -q "\-auto"
   if [ $? -eq 0 ];
   then
      composer_automated=0 #0 equals true
      ARGSLIST="$(echo "$ARGSLIST" | sed -e 's/\(^\| \)-auto\($\| \)//')"
      logstr "Automated upgrade by composer."
   else
      composer_automated=1 #1 equals false
   fi
#</CheckComposerFlag>

mynode="`uname -n`"
primvar=node_1_name
secvar=node_2_name
getcfgvar $CFG8k test_bed             testbed
getcfgvar $CFG8k $primvar             primhost
getcfgvar $CFG8k $secvar              sechost

if [ "$mynode" = "$primhost" ];
then
   othernode=$sechost
else
   othernode=$primhost
   logstr "This script needs to be run from $primhost"
   exit $Fail
fi

#<CleanupUploadDirectory> \\OSV-11706
   if [ $composer_automated -eq 0 ];
   then
      logstr "About to perfom file cleanup of ${REPOSITORY}/upload/ on $mynode. All files in ${REPOSITORY}/upload/ will be lost except the files under auto."
      if [ ! -d ${REPOSITORY}/upload/auto ]; 
      then
	 logstr "${REPOSITORY}/upload/auto does not exist on $mynode."
	 exit $Fail
      fi
      find ${REPOSITORY}/upload/ -mindepth 1 -maxdepth 1 ! -path "${REPOSITORY}/upload/auto" -exec rm -rf {} \;
      if [ $? -ne 0 ];
      then
         logstr "Could not perform cleanup of ${REPOSITORY}/upload on $mynode."
	 exit $Fail
      fi
      mv ${REPOSITORY}/upload/auto/* ${REPOSITORY}/upload/ && rmdir ${REPOSITORY}/upload/auto/
      if [ $? -ne 0 ];
      then
	 logstr "Could not restore upgrade files to ${REPOSITORY}/upload on $mynode."
	 exit $Fail
      fi
	 
      if [ "$testbed" = "cluster" ];
      then
	 logstr "About to perfom file cleanup of ${REPOSITORY}/upload/ on $othernode. All files in ${REPOSITORY}/upload/ will be lost except the files under auto."
	 ssh -o ConnectTimeout=8 clusternode2-priv "test -d ${REPOSITORY}/upload/auto"
	 if [ $? -ne 0 ];
	 then
	    logstr "${REPOSITORY}/upload/auto does not exist on $othernode."
	    exit $Fail
	 fi
	 ssh -o ConnectTimeout=8 clusternode2-priv "find ${REPOSITORY}/upload/ -mindepth 1 -maxdepth 1 ! -path \"${REPOSITORY}/upload/auto\" -exec rm -rf {} \\;"
	 if [ $? -ne 0 ];
	 then
            logstr "Could not perform cleanup of ${REPOSITORY}/upload on $othernode."
	    exit $Fail
	 fi
	 ssh -o ConnectTimeout=8 clusternode2-priv "mv ${REPOSITORY}/upload/auto/* ${REPOSITORY}/upload/ && rmdir ${REPOSITORY}/upload/auto/"
	 if [ $? -ne 0 ];
	 then
	    logstr "Could not restore upgrade files to ${REPOSITORY}/upload on $othernode."
	    exit $Fail
	 fi
      fi
   fi
#<CleanupUploadDirectory>

#<RemoveExistingTk>
   for idx in `rpm -aq | grep UNSPmigration | sort -r`
   do
      logstr "Removing ${idx} on $mynode."
      rpm -e --allmatches $idx 1>>$LOGFILE 2>&1
      if [ $? -ne 0 ];
      then
         logstr "Could not uninstall toolkit on $mynode."
         exit $Fail
      fi
   done
   if [ "$testbed" = "cluster" ];
   then
      outstr=$(ssh -o ConnectTimeout=8 clusternode2-priv '
         for idx in `rpm -aq | grep UNSPmigration | sort -r`
         do 
            echo "Removing $idx on '"$othernode"'."
            rpm -e --allmatches "$idx" 1>>'"$LOGFILE"' 2>&1
         done
      ')
      tmpexit=$?
      logstr "$outstr"
      if [ $tmpexit -ne 0 ];
      then
         logstr "Could not uninstall toolkit on $othernode."
         exit $Fail
      fi
   fi
#</RemoveExistingTk>

#<InstallNewTk>
   numtk=`ls ${REPOSITORY}/upload/UNSPmigration*.rpm 2>/dev/null | wc -l`
   tk=`ls ${REPOSITORY}/upload/UNSPmigration*.rpm 2>/dev/null | sort -nr | head -1`
   if [ $numtk -eq 0 ];
   then
      logstr "No toolkit under ${REPOSITORY}/upload."
      exit $Fail
   fi
   if [ $numtk -gt 1 ];
   then
      logstr "Many toolkits under ${REPOSITORY}/upload."
      exit $Fail
   fi
   if [ "$testbed" = "cluster" ];
   then
      logstr "Copying toolkit to $othernode."
      scp -p -o ConnectTimeout=8 ${tk} clusternode2-priv:${tk} 1>>$LOGFILE 2>&1
      if [ $? -ne 0 ];
      then
         logstr "Could not copy toolkit to $othernode."
         exit $Fail
      fi
   fi
   logstr "Installing toolkit on $mynode."
   rpm -i --replacefiles --replacepkgs $tk 1>>$LOGFILE 2>&1
   if [ $? -ne 0 ];
   then
      logstr "Could not install toolkit to $mynode."
      exit $Fail
   fi
   if [ "$testbed" = "cluster" ];
   then
      logstr "Installing toolkit on $othernode."
      ssh  -o ConnectTimeout=8 clusternode2-priv "
         rpm -i --replacefiles --replacepkgs $tk 1>>$LOGFILE 2>&1
      "
      if [ $? -ne 0 ];
      then
         logstr "Could not install toolkit to $othernode."
         exit $Fail
      fi
   fi
#</InstallNewTk>

#<CheckRPMInstall>
   if [ "$1" = "-u" ];
   then
      logstr "Toolkit package was successfully installed"
      exit 0
   fi
#<CheckRPMInstall>

#<CheckQuietMode>
   echo "$ARGSLIST" | egrep -q "\-quiet"
   if [ $? -ne 0 ];
   then
      ARGSLIST="-quiet $ARGSLIST"
   fi
#</CheckQuietMode>

#<CopyNodeCfgToUploadDir> \\OSV-10551
   if [ $composer_automated -eq 0 ];
   then
      logstr "Copying node.cfg to ${REPOSITORY}/upload on $mynode."
      if [ $(ls ${REPOSITORY}/upload | grep  '^V[0-9]\+_.*\.iso$' | wc -l) -ne 1 ];
      then
	 logstr "Could not copy node.cfg, there should only be one iso image in ${REPOSITORY}/upload on $mynode."
	 exit $Fail
      fi 
      cp ${REPOSITORY}/config/"$(ls ${REPOSITORY}/upload | grep '^V[0-9]\+_.*\.iso$' | cut -d_ -f1)"*/node.cfg ${REPOSITORY}/upload/node.cfg.primary
      if [ $? -ne 0 ];
      then
	 logstr "Could not copy node.cfg to ${REPOSITORY}/upload on $mynode."
	 exit $Fail
      fi
      if [ "$testbed" = "cluster" ];
      then
	 logstr "Copying node.cfg to ${REPOSITORY}/upload on $othernode."
	 scp -p -o ConnectTimeout=8 ${REPOSITORY}/upload/node.cfg.primary clusternode2-priv:${REPOSITORY}/upload/node.cfg.secondary 1>>$LOGFILE 2>&1
	 if [ $? -ne 0 ];
	 then
            logstr "Could not copy node.cfg to ${REPOSITORY}/upload on $othernode."
            exit $Fail
	 fi
      fi
   fi
#</CopyNodeCfgToUploadDir>


pushd $REPOSITORY/upload
nohup upgrade8k $ARGSLIST 1>/dev/null 2>&1 &
sleep 4
logstr "Done."
