#!/bin/bash

# -------------------------------------------------------
# file   : migrate8k.sh
# purpose: Installation script to migrate data from system.
# author : Vittal.S
#
# usage  : migrate8k
#
# modifications:
# 09-05-08  Initial Creation .
# -------------------------------------------------------

### Constants
_SELF_="$(basename "$(readlink -e "${BASH_SOURCE[0]}")" && echo X)" && \
readonly _SELF_="${_SELF_%$'\nX'}"
_SELFDIR_="$(dirname "$(readlink -e "${BASH_SOURCE[0]}")" && echo X)" && \
readonly _SELFDIR_="${_SELFDIR_%$'\nX'}"
readonly COMMONINC="${_SELFDIR_}/common8k"

chmod o+r /etc/login.defs

### Include files
source ${COMMONINC} || exit 1
#Check if osv_version is available
OSV_VERSION=$(whereis -b osv_version.sh | awk '{ print $2 }')
if [ ! -f "$OSV_VERSION" ]; then
   logger --id $$ --priority user.warning "$0: osv_version.sh not found in \$PATH ($PATH), exiting!" >/dev/null 2>&1
   exit 1
fi

# ----------------------------------------------------------------
# function: rssh
# args    : none
# description:
#   Make sure  to execure command for partner only in regular mode.
# ----------------------------------------------------------------

rssh( )
{
   if [ "$RECOVER8k" = "" -a "$LIVE8kUPGRADE" = "" ];
   then
      logdebug "Executing command [${*}] via SSH"
      ssh $*
   else
      echo "   - Skipping ssh to partner"
   fi
} 2>/dev/null

rscp( )
{
   if [ "$RECOVER8k" = "" -a "$LIVE8kUPGRADE" = "" ];
   then
      logdebug "File copy command [${*}] via SSH"
      scp $*
   else
      echo "   - Skipping scp to partner"
   fi
} 2>/dev/null

# ----------------------------------------------------------
# function: checkrecovery
# description:
#   checks for recovery mode. Toolkit will try to help you
#   if your hardware on one node failed.
# ----------------------------------------------------------

checkrecovery( )
{
   if [ "$testbed" = "cluster" ];
   then
      textncolor $BoldCyan "migrate8k: Checking if partner node is alive."
      prepare8k -quiet -ping 1>>/log/check8k.log 2>&1
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed   "migrate8k: Remote node is not alive!."
         textncolor $BoldGreen "Hint: Please Check toolkit is installed on both nodes."
         echo                "    : run rpm -q UNSPmigration as user root to check this.!"

         if [ "$INTERACTIVE8k" = "false" ];
         then
            textncolor $BoldGreen "migrate8k: You have two options."
            textncolor $BoldCyan  "Warning: Use recovery mode only if you are sure of partner node failure!."
            echo "   - [1]. Run migrate in recovery mode. Only Data on current node will be migrated."
            echo "   - [2]. Exit. No action."
            echo -n "   - Enter (1=Recover,2=Exit) : "
            read answer
            if [ "$answer" -eq "1" ];
            then
               RECOVER8k="-recover"
            else
	       keeptrack "Migrate failed: checkrecovery()"
               exit $FAIL
            fi
         else
	    keeptrack "Migrate failed: checkrecovery()"
            exit $FAIL
         fi
      fi
   fi
}

# ---------------------------------------------------------------
# function: initvars
# args    : None
# description:
#   just initialize one variables.
# ---------------------------------------------------------------

initvars( )
{
   SUCCESS=0
   FAIL=2
   MISSINGCFGDIR=8

   BoldGreen="\033[1;32m"
   BoldBlue="\033[1;34m"
   BoldCyan="\033[1;36m"
   BoldWhite="\033[1;37m"
   BoldRed="\033[1;31m"
   UnderLine="\033[4m"
   Yellow="\033[1;33m"
   Norm="\033[0m"

   checkpwd

   PROC=migrate8k
   CFG8k=/etc/hiq8000/node.cfg
   LOGFILE=/log/prepare8k.log

   USER=`id -u`
   if [ $USER -ne 0 ];
   then
       echo "You  must be root to run this script."
       exit $FAIL
   fi

   #<CheckRSU>
      oplock check
      if [ $? -ne 0 ];
      then
         currentpid=$$
         parentpid=`ps -p $currentpid -o ppid=| sed -e 's/ //g'`
         grandparentpid=`ps -p $parentpid -o ppid=| sed -e 's/ //g'`
         runpids=`pgrep upgrade8k`
         pidstatus=2
         for idx in $currentpid $parentpid $grandparentpid
         do
            if [ "$idx" = "$runpids" ];
            then
               pidstatus=0
               break;
            fi
         done
         if [ $pidstatus -ne 0 ];
         then
            nupgrade=`ps -ef f | grep upgrade8k |                \
                      egrep -v "\-s|\-h|vi|less|more|cat|lock" | \
                      grep -v grep | wc -l`
            if [ "$nupgrade" -ge 2 ];
            then
               echo "> Following processes are running."
               ps -eo pid,command | grep upgrade8k |  grep -v grep
               textncolor $BoldRed "migrate8k: Upgrade or fallback in progress. Exiting now."
               textncolor $BoldRed "        : Wait for upgrade or fallback to complete."
               exit $FAIL
            fi
         fi
      fi
      oplock clean
   #</CheckRSU>

   mynode="`uname -n`"
   getcfgvar $CFG8k test_bed testbed
   getcfgvar $CFG8k node_1_name primhost
   getcfgvar $CFG8k node_2_name sechost
   nafoxch="`cfgread nafo3`"
   if "$OSV_VERSION" --major compare sys lt V5;
   then
      getcfgvar $CFG8k node_1_cip_logical primcip
      getcfgvar $CFG8k node_2_cip_logical seccip
   else
      primcip="`echo $nafoxch   | awk '{ print $4 }'`"
      seccip="`echo $nafoxch    | awk '{ print $5 }'`"
   fi
   
   if [ "$mynode" = "$primhost" ];
   then
      othernode=$sechost
   else
      othernode=$primhost
   fi

   export Migrate8kOnly=true
   export INTERACTIVE8k=true
   RECOVER8k=""
   LOCAL4USB=false
   LIVE8kUPGRADE=""

   activeinfo="`sync8k -q none`"
   activenotrail=${activeinfo%,*}
   activeimg=${activenotrail#*:}
   passiveimg=${activeinfo#*Fallback:}

   #<GetUpgradeMode>
      upgrademode="`cat /img/logimg/${passiveimg}/upgrade.lock 2>/dev/null`"
      if [ "$upgrademode" = "" ];
      then
         iptables -nL firewall 1>/dev/null 2>&1
         if [ $? -eq 0 ];
         then
            upgrademode="OutageFree"
         else
            upgrademode="Outage"
         fi
      fi
   #</GetUpgradeMode>

   if [ "$upgrademode" != "OutageFree" ];
   then
      checkinstalldone
      checkrecovery
   fi
}


### MAIN LOGIC
debug_info_startup_script

ARGLIST="$*"
timerstart=$(jobtimer)
initvars
while [ "$#" -gt "0" ];
do
   case $1 in
      -cfg)
          shift
          export CFGMNTPATH=$1
          if [ "$CFGMNTPATH" = "" ];
          then
              textncolor $BoldCyan "Sorry, Specify the cfg path where exported data will be placed."
              exit $MISSINGCFGDIR 
          fi
          textncolor $BoldCyan "Migrated data will be retrieved from $CFGMNTPATH"
          ;;
      -password)
          textncolor $BoldCyan "Passwords from older version will be restored."
          ;;
      -config)
          textncolor $BoldCyan "Config data from older version will be restored."
          ;;
      -nosec)
          textncolor $BoldCyan "Custom Security rules will be skipped."
          ;;
      -nosym)
          textncolor $BoldCyan "Database will not contain symphonia tables."
          export NOSYMPHONIA=true
          ;;
      -nopassword)
          textncolor $BoldCyan "Passwords from newer version will be used."
          ;;
      -clusterip)
          textncolor $BoldCyan "Cip's from newer version will be restored."
          ;;
      -billingip)
          textncolor $BoldCyan "Billingip's from newer version will be restored."
          ;;
      -ntp)
          textncolor $BoldCyan "Ntp information from newer version will be restored."
          ;;
      -noapps)
          textncolor $BoldCyan "Applications will be removed."
          echo -n "Do you want to preserve the application data in db for later migration [y/n]: "
          clearstdin
          read zanswer
          if [ "$zanswer" = "N" -o "$zanswer" = "n" ];
          then
            AUXARGLIST="$AUXARGLIST -noappsindb "
          fi
          #<SetupRespFile>
          if [ -f /etc/hiq8000/response.cfg ];
          then
             echo ""
             echo "/////////////////////// Important /////////////////////////////////"
             echo "----------------------  Information -------------------------------"
             echo "Please Note: At the end migrate,a response file will be setup for you."
             echo "This file is located at /etc/hiq8000/response.cfg."
             echo "User must use this file while installing applications."
             echo "///////////////////////////////////////////////////////////////////"
             echo -n "Press enter to continue : "
             clearstdin
             read zanswer
          fi
          #</SetupRespFile>
          ;;
      -quiet)
          textncolor $BoldGreen "Information: Quiet mode. No interaction on errors."
          INTERACTIVE8k=false
          ;;
      -recover)
          RECOVER8k="-recover"
          ;;
      -local)
          textncolor $BoldCyan "Migrated data extracted locally!."
          LOCAL4USB=true
          ;;
      -zen)
          textncolor $BoldCyan "Checking node.cfg."
          prepare8k -zen
          exit $?
          ;;
      -live)
          LIVE8kUPGRADE="-live"
          ;;
      -isonlyone)
	  isOnlyOne
	  exit $?
	  ;;
         *)
           textncolor $BoldCyan "Sorry, Unknown option."
           echo "Usage: migrate8k [-cfg]"
           exit $FAIL
           ;;
   esac
   shift
done

# Make sure this is the only job running. Check cluster only if it's not a liveupgrade
if isOnlyOne
then
   :
else
   textncolor $BoldCyan "migrate8k: Another migrate8k job already running on $mynode: pid - $PID_JOB_RUNNING"
   echo                 ">Info"
   cat                  $INFLOG 2>/dev/null
   textncolor $BoldRed  "migrate8k: Terminate existing running job or wait for its completion."
   keeptrack "Migrate failed: isOlyOne()"
   exit $FAIL
fi

if [ "$testbed" = "cluster" -a "$LIVE8kUPGRADE" = "" ];
then
   #<CheckRemoteAdmin>
      if [ "$RECOVER8k" = "" ];
      then
         rssh -o ConnectTimeout=8 $othernode "id" 1>/dev/null 2>&1
         if [ $? -ne 0 ];
         then
             textncolor $BoldRed  "migrate8k: Remote node $othernode(Admin network) is not alive."
             exit $FAIL
         fi
      fi
   #</CheckRemoteAdmin>

   rssh $othernode "migrate8k -isonlyone" 1>/dev/null 2>&1
   if [ $? -ne 0 ];
   then
      scp $othernode:$PIDLOG /tmp 2>/dev/null
      scp $othernode:$INFLOG /tmp 2>/dev/null
      PID_JOB_RUNNING="`cat $PIDLOG`"
      textncolor $BoldCyan "migrate8k: Another migrate8k job already running on $othernode: pid - $PID_JOB_RUNNING"
      echo                 ">Info"
      cat                  $INFLOG 2>/dev/null
      textncolor $BoldRed  "migrate8k: Terminate existing running job or wait for its completion."
      keeptrack "Migrate failed: isOnlyOne()"
      exit $FAIL
   fi
fi

if [ "$testbed" = "cluster" -a "$mynode" != "$primhost" ];
then
   textncolor $BoldCyan "migrate8K: O.k you are on secondary node of cluster. Will still proceed."
   textncolor $BoldCyan "migrate8K: Checking if exported data exists."
   if [ "$CFGMNTPATH" != "" ];
   then
      rssh $primcip "prepare8k $RECOVER8k -cfg $CFGMNTPATH -check" 1>>/log/check8k.log 2>&1
   else
      if [ "$LOCAL4USB" = "false" ];
      then
         rssh $primcip "prepare8k $RECOVER8k -check" 1>>/log/check8k.log 2>&1
      else
         rssh $primcip "prepare8k $RECOVER8k -local -check" 1>>/log/check8k.log 2>&1
      fi
   fi

   if [ $? -ne 0 ];
   then
      expdevice=${CFGMNTPATH:-"USB"}
      textncolor $BoldRed "Migrate failed: Missing exported data or node.cfg under $expdevice."
      textncolor $BoldRed "              : See /log/check8k.log for more details."
      keeptrack "Migrate failed: Missing exported data"
      exit $FAIL
   fi
   rssh $primcip "prepare8k $RECOVER8k $ARGLIST $AUXARGLIST -migrate"
   status=$?
   if [ $status -ne 0 ];
   then
      textncolor $BoldRed "Migrate failed: `date`"
   else
      rm -f  /log/unlock8k.log
      rssh $primcip "prepare8k $RECOVER8k -unlock" 1>>/log/unlock8k.log 2>&1
      textncolor $BoldCyan "Migrate completed: `date`"
      keeptrack "Migrate completed successfully"
   fi
else
   textncolor $BoldCyan "migrate8K: Checking if exported data exists."
   logdebug "Migration files under [${CFGMNTPATH:-USB device}]"
   if [ "$CFGMNTPATH" != "" ];
   then
      prepare8k $RECOVER8k -cfg $CFGMNTPATH -check 1>>/log/check8k.log 2>&1
   else
      if [ "$LOCAL4USB" = "false" ];
      then
         prepare8k $RECOVER8k -check 1>>/log/check8k.log 2>&1
      else
         prepare8k $RECOVER8k -local -check 1>>/log/check8k.log 2>&1
      fi
   fi
   if [ $? -ne 0 ];
   then
      expdevice=${CFGMNTPATH:-"USB"}
      textncolor $BoldRed "Migrate failed: Missing exported data or node.cfg under $expdevice."
      textncolor $BoldRed "              : See /log/check8k.log for more details."
      keeptrack "Migrate failed: Missing exported data"
      exit $FAIL
   fi
   
   # Perform the migration with prepare8k
   logdebug "RECOVER8k: [${RECOVER8k}], ARGLIST: [${ARGLIST}], AUXARGLIST: [${AUXARGLIST}]"
   
   prepare8k $RECOVER8k $ARGLIST $AUXARGLIST -migrate
   
   status=$?
   logdebug "Command [prepare8k $RECOVER8k $ARGLIST $AUXARGLIST -migrate] returned exit code [${status}]"
   if [ $status -ne 0 ];
   then
      textncolor $BoldRed "Migrate failed: `date`"
   else
      rm -f  /log/unlock8k.log
      prepare8k $RECOVER8k -unlock 1>>/log/unlock8k.log 2>&1
      textncolor $BoldCyan "Migrate completed: `date`"
      keeptrack "Migrate completed successfully"
   fi
fi
textncolor $BoldCyan "Elapsed time: $(jobtimer $timerstart)"
exit $status
