#!/bin/bash

# -------------------------------------------------------
# file   : bring8k.sh
# purpose: Script to bring exported data into the system
# author : Vittal.S
#
# 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
      ssh $*
   else
      echo "   - Skipping ssh to partner"
   fi
} 2>/dev/null

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

# ---------------------------------------------------------------
# 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=import8k
   CFG8k=/etc/hiq8000/node.cfg
   LOGFILE=/log/prepare8k.log
   export LOG8k4TOOLKIT=${LOGFILE}

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

   if processCalledByImageUpgrade "$$";
   then
      export LOG8k4TOOLKIT=""
   fi

   #<CheckRSU>
      oplock check
      if [ $? -ne 0 ];
      then
         local pid=$$
         local pidstatus=2
         local runpids=$(pgrep upgrade8k)

         local allpids="${pid} $(getAllAncestors "${pid}")"

         for idx in ${allpids}
         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 "import8k: 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`"
   primvar=node_1_name
   secvar=node_2_name

   getcfgvar $CFG8k test_bed testbed
   getcfgvar $CFG8k $primvar primhost
   getcfgvar $CFG8k $secvar  sechost
   
   nafoxch="`cfgread nafo3`"

   primcip="`echo $nafoxch   | awk '{ print $4 }'`"
   seccip="`echo $nafoxch    | awk '{ print $5 }'`"
      
   
   if [ "$mynode" = "$primhost" ];
   then
      othernode=$sechost
   else
      othernode=$primhost
   fi

   export Import8kOnly=true
   RECOVER8k=""
   LOCAL4USB=false
   export INTERACTIVE8k=true
   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
}

# ----------------------------------------------------------
# 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
      count=0
      textncolor $BoldCyan "import8k: Checking if partner node is alive."
      while ( true )
      do
         prepare8k -quiet -ping 1>>/log/check8k.log 2>&1
         if [ $? -ne 0 ];
         then
            count=$[count+1]
            if [ $count -gt 64 ]; 
            then
               textncolor $BoldRed   "import8k: 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 "import8k: You have two options."
                  textncolor $BoldCyan  "Warning: Use recovery mode only if you are sure of partner node failure!"
                  echo "   - [1]. Run import in recovery mode. Only Data on current node will be imported."
                  echo "   - [2]. Exit. No action."
                  echo -n "   - Enter (1=Recover,2=Exit) : "
                  read answer
                  if [ "$answer" -eq "1" ];
                  then
                     RECOVER8k="-recover"
                  else
      	          keeptrack "Import failed: checkrecovery()"
                     exit $FAIL
                  fi
               else
      	         keeptrack "Import failed: checkrecovery()"
                  exit $FAIL
               fi
            else
               echo "[import8k] Waiting for partner node to come online(attempt:$count+)."
               sleep 16
               continue;
            fi
         else
            break;
         fi
      done
   fi
}

ARGLIST="$*"
AUXARGLIST=""
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 imported data will be retrieved."
              exit $MISSINGCFGDIR 
          fi
          textncolor $BoldCyan "Imported data will be retrieved from $CFGMNTPATH"
          ;;
      -password)
          textncolor $BoldCyan "Passwords from older version will be restored."
          ;;
      -quiet)
          textncolor $BoldGreen "Information: Quiet mode. No interaction on errors."
          export INTERACTIVE8k=false
          ;;
      -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."
          ;;
      -nodename)
          textncolor $BoldCyan "Nodename information will be adjusted."
          ;;
      -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 end of import, 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>
          ;;
      -recover)
          RECOVER8k="-recover"
          ;;
      -local)
          textncolor $BoldCyan "Imported 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: import8k [-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 "import8k: Another import8k job already running on $mynode: pid - $PID_JOB_RUNNING"
   echo                 ">Info"
   cat                  $INFLOG 2>/dev/null
   textncolor $BoldRed  "import8k: Terminate existing running job or wait for its completion."
   keeptrack "Import failed: isOnlyOne()"
   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  "import8k: Remote node $othernode(Admin network) is not alive."
             exit $FAIL
         fi
      fi
   #</CheckRemoteAdmin>
   rssh -o ConnectTimeout=8 $othernode "import8k -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 "import8k: Another import8k job already running on $othernode: pid - $PID_JOB_RUNNING"
      echo                 ">Info"
      cat                  $INFLOG 2>/dev/null
      textncolor $BoldRed  "import8k: Terminate existing running job or wait for its completion."
      keeptrack "Import failed: isOnlyOne()"
      exit $FAIL
   fi
fi

if [ "$testbed" = "cluster" -a "$mynode" != "$primhost" -a "$LIVE8kUPGRADE" = "" ];
then
   textncolor $BoldCyan "import8k: O.k you are on secondary node of cluster. Will still proceed."
   textncolor $BoldCyan "import8k: Checking if exported data exists."
   if [ "$CFGMNTPATH" != "" ];
   then
      rssh $primcip "prepare8k $RECOVER8k $LIVE8kUPGRADE -cfg $CFGMNTPATH -check" 1>>/log/check8k.log 2>&1
   else
      if [ "$LOCAL4USB" = "false" ];
      then
        rssh $primcip "prepare8k $RECOVER8k $LIVE8kUPGRADE -check" 1>>/log/check8k.log 2>&1
      else
        rssh $primcip "prepare8k $RECOVER8k $LIVE8kUPGRADE -local -check" 1>>/log/check8k.log 2>&1
      fi
   fi
   if [ $? -ne 0 ];
   then
      expdevice=${CFGMNTPATH:-"usb"}
      textncolor $BoldRed "Import failed: Missing exported data or node.cfg under $expdevice."
      textncolor $BoldRed "             : See /log/check8k.log for more details."
      keeptrack "Import failed: Missing exported data"
      exit $FAIL 
   fi
   rssh $primcip "prepare8k $RECOVER8k $LIVE8kUPGRADE $ARGLIST $AUXARGLIST -import"
   status=$?
   if [ $status -ne 0 ];
   then
      textncolor $BoldRed "Import failed: `date`"
   else
      rm -f  /log/unlock8k.log
      rssh $primcip "prepare8k $RECOVER8k $LIVE8kUPGRADE -unlock" 1>>/log/unlock8k.log 2>&1
      textncolor $BoldCyan "Import completed: `date`"
      keeptrack "Import completed successfully"
   fi
else
   textncolor $BoldCyan "import8k: Checking if exported data exists."
   if [ "$CFGMNTPATH" != "" ];
   then
      prepare8k $RECOVER8k $LIVE8kUPGRADE -cfg $CFGMNTPATH -check 1>>/log/check8k.log 2>&1
   else
      if [ "$LOCAL4USB" = "false" ];
      then
         prepare8k $RECOVER8k $LIVE8kUPGRADE -check 1>>/log/check8k.log 2>&1
      else
         prepare8k $RECOVER8k $LIVE8kUPGRADE -local -check 1>>/log/check8k.log 2>&1
      fi
   fi
   if [ $? -ne 0 ];
   then
      expdevice=${CFGMNTPATH:-"usb"}
      textncolor $BoldRed "Import failed: Missing exported data or node.cfg under $expdevice."
      textncolor $BoldRed "             : See /log/check8k.log for more details."
      keeptrack "Import failed: Missing exported data"
      exit $FAIL 
   fi
   prepare8k $RECOVER8k $LIVE8kUPGRADE $ARGLIST $AUXARGLIST -import
   status=$?
   if [ $status -ne 0 ];
   then
      textncolor $BoldRed "Import failed: `date`"
   else
      rm -f  /log/unlock8k.log
      prepare8k $RECOVER8k $LIVE8kUPGRADE -unlock 1>>/log/unlock8k.log 2>&1
      textncolor $BoldCyan "Import completed: `date`"
      keeptrack "Import completed successfully"
   fi
fi
textncolor $BoldCyan "Elapsed time: $(jobtimer $timerstart)"
exit $status
