#!/bin/sh

. /opt/hmc/bin/functions

scanCFG() {
  OP=`grep optype $CFG_FILE | cut -f2 -d "="| sed -e 's/ //g'`
  MEDIA=`grep media $CFG_FILE | cut -f2 -d "="| sed -e 's/ //g'`
  R_HOST=`grep host $CFG_FILE | cut -f2 -d "="| sed -e 's/ //g'`
  TRANS=`grep transtype $CFG_FILE | cut -f2 -d "="| sed -e 's/ //g'`
  HOST=`grep host $CFG_FILE | cut -f2 -d "="| sed -e 's/ //g'`
  XDIR=`grep xdir $CFG_FILE | cut -f2 -d"=" | sed -e 's/ //g'`
  USER=`grep userid $CFG_FILE | cut -f2 -d"=" | sed -e 's/ //g'`
  PASSWD=`grep passwd $CFG_FILE | cut -f2 -d"=" | sed -e 's/ //g'`
  INTERFACE=`grep interface $CFG_FILE | cut -f2 -d"=" | sed -e 's/ //g'`
  IPADDRESS=`grep ipaddr $CFG_FILE | cut -f2 -d"=" | sed -e 's/ //g'`
  NETMASK=`grep netmask $CFG_FILE | cut -f2 -d"=" | sed -e 's/ //g'`
  GATEWAY=`grep gateway $CFG_FILE | cut -f2 -d"=" | sed -e 's/ //g'`
  NAMESERVER=`grep dns $CFG_FILE | cut -f2 -d"=" | sed -e 's/ //g'`
  PROTOCOL=`grep protocol $CFG_FILE | cut -f2 -d"=" | sed -e 's/ //g'`
}

updategrub()
{
  echo "Configuring GRUB......"
  echo -e "device (hd0) /dev/${HD}\nroot (hd0,1)\nsetup (hd0)" | grub --batch > /tmp/grub.out 2>&1
}

updategrub2()
{
  grubdev=/dev/${HD}

  echo "Configuring GRUB2....."
  if [ "$march" = "ppc64le" ]; then
    grubdev=/dev/${HDP}1
    dd if=/dev/zero of="$grubdev"
  fi
  chroot /hmc chmod -x /etc/grub.d/10_linux
  chroot /hmc chmod -x /etc/grub.d/20_linux_xen
  chroot /hmc chmod -x /etc/grub.d/40_custom
  chroot /hmc chmod -x /etc/grub.d/41_custom
  echo "chroot /hmc /usr/sbin/grub2-install -v $grubdev" >> /hmc/tmp/grub2-install.log 2>&1
  chroot /hmc /usr/sbin/grub2-install -v $grubdev >> /hmc/tmp/grub2-install.log 2>&1
  chroot /hmc mount >> /hmc/tmp/grub2-install.log 2>&1
  chroot /hmc uname -a >> /hmc/tmp/grub2-install.log 2>&1
  chroot /hmc /usr/sbin/grub2-mkconfig -o /boot/grub2/grub.cfg
  chroot /hmc rm -rf /boot/grub >> /dev/null 2>&1

  if [ "$march" = "ppc64le" ]; then
    hypervsr=$(/opt/hmc/bin/gethypervisorinfo)
    if [ "$hypervsr" = "POWERNV" ]; then
      rootfsdev=$(blkid | awk -F: '/TYPE="ext[34]"/ && /LABEL="rootfs"/ {print $1}')
      eval $(blkid -o export $rootfsdev | grep ^UUID)
      if [ -n "$UUID" ]; then
        nvram --update-config=petitboot,bootdev=uuid:$UUID
        nvram --update-config=petitboot,bootdevs=uuid:$UUID
      fi
      if ! nvram --print-config=petitboot,timeout &>/dev/null; then
        nvram --update-config=petitboot,timeout=10
      fi
      if ! nvram --print-config=petitboot,console &>/dev/null; then
        nvram --update-config=petitboot,console="/dev/tty1 [VGA]"
      fi
      if nvram --print-config='auto-boot?' &>/dev/null; then
        nvram --update-config='auto-boot?='
      fi
    elif [ "$hypervsr" = "POWERVM" ]; then
      # Set boot device to reboot from disk
      fwdev=$(ofpathname /dev/${HD})
      # Determine if there are any disks part of multipath io disk
      # with unique open firmware path name. If so they all need
      # to be added to bootdev in order to boot in case one path
      # is down
      addtldev=$(multipathd show paths raw format "%d" 2>/dev/null)
      if [ ! -z "$addtldev" ]; then
          for i in $addtldev; do
              pn=$(ofpathname /dev/$i)
              if [[ ":$fwdev:" != *"$pn"* ]]; then
                  fwdev=$fwdev" "$pn
              fi
          done
      fi
      if [ ! -z "$fwdev" ]; then
        nvram --update-config boot-device="$fwdev"
      fi
    fi
  fi

}

enableMultipathBoot() {
  if ! grep -q r/block/ /hmc/lvm/lvm.conf 2>/dev/null; then
    chroot /hmc sed -i '/Configuration option devices\/global_filter/i\\tfilter = [ "r/block/", "r/disk/", "r/sd.*/", "a/.*/" ]' /etc/lvm/lvm.conf
  fi
  chroot /hmc systemctl enable multipathd
}

#------------ M A I N ---------------------
CFG_FILE="/opt/hmc/data/HmcInstall.cfg"

cp $CFG_FILE /root/HmcInstall.cfg.saved

echo "Processing Commands ......"

scanCFG

#UPGR_FILE="/mnt/upgrade/SaveHSCSystemUpgradeData.tar"
#RSTR_FILES="/etc/localtime /etc/sysconfig/clock"
RESULT="Failed"
RET_CODE=1
HD=`/opt/hmc/bin/getHDName`
# if $HD ends with a number, then add p
if [[ "${HD: -1}" =~ ^[0-9]$ ]]; then
    HDP="${HD}p"
else
    HDP="${HD}"
fi
PRTN="/dev/${HD}"

#
if [ "$OP" = "Install" ]; then
  if [ "$MEDIA" != "disk" ]; then
    /opt/hmc/bin/initDisk
    HD=$(/opt/hmc/bin/getHDName)
    # if $HD ends with a number, then add p
    if [[ "${HD: -1}" =~ ^[0-9]$ ]]; then
        HDP="${HD}p"
    else
        HDP="${HD}"
    fi
  fi
fi
if [ "$OP" = "Upgrade" ]; then
  echo "Processing Upgrade  ......"
  UPGR="Yes"
  # save a copy of current passwd and group files in memory
  mkdir -p /tmpmnt
  mkdir -p /tmpetc
  mount -t ext3 /dev/${HDP}2 /tmpmnt
  cp /tmpmnt/etc/passwd /tmpetc/
  cp /tmpmnt/etc/group  /tmpetc/
  umount /tmpmnt
  # save a copy of install cfg file in memory
  cp $CFG_FILE /tmpetc
else
  UPGR="No"
fi

march=`uname -m`
if [ "$march" = "x86_64" ]; then
  # create grub2 space in case we are coming from grub env
  createGrub2Space
fi
cd /
/opt/hmc/bin/MakeHmcFS $OP $MEDIA $UPGR

############################
# making some necessary directories on the root filesystem
############################
[ -d /hmc/media/cdrom ] || mkdir -p /hmc/media/cdrom
[ -d /hmc/media/floppy ] || mkdir -p /hmc/media/floppy

############################
# installing base.img
############################
cd /base
echo "Installing Base Operating System..."
tar cf - . 2>/dev/null | (cd /hmc && tar xBf - --checkpoint=35000 --checkpoint-action=exec="echo Installing Base Operating System...")
rc=$?
cd /
if [ "$rc" != "0" ]; then
  exit 10
fi

vdisk=`echo ${HD} | cut -c1-2`
if [ "${vdisk}" == "vd" ]; then
  echo "(fd0)  /dev/fd0" > /hmc/boot/grub/device.map
  echo "(hd0)  /dev/${HD}" >> /hmc/boot/grub/device.map
  cp /hmc/boot/grub/device.map /hmc/boot/grub2/
  cp /hmc/boot/grub/splash.xpm.gz /hmc/boot/grub2/
fi

if [ "$OP" = "Upgrade" ]; then
  # copy passwd, group, and install cfg files from memory to /hmc
  [ -d /hmc/tmpetc ] || mkdir -p /hmc/tmpetc
  cp /tmpetc/* /hmc/tmpetc/
fi

TMP=/tmp/sedout
FTAB=/hmc/etc/fstab
cp /opt/hmc/data/fstab $FTAB
cd /

############################
# installing disk1.img
# Need to run applyUpdates here to ensure
# that disk1.img is signed properly
############################
[ -d /hmc/dump/hsc_install.images ] || mkdir /hmc/dump/hsc_install.images
[ -d /hmc/dump/cdrom ] || mkdir /hmc/dump/cdrom
if [ "$MEDIA" == "network" ]; then
  mount -o loop /sysroot/disk1.img /hmc/dump/hsc_install.images
elif [ "$MEDIA" == "disk" ]; then
  mkdir -p /tmp/mnt
  #  We get here, the base OS has been installed
  #  Proceed to install the HMC code on /hmcdump
  #  Ensure label is present
  LABELNAME=${HMCDUMPPARTITION#\/}
  lbl=`e2label ${LABELNAME:-rootfs}`
  if [ "$lbl" != "/hmcdump" ]; then
    tune2fs -L /hmcdump ${HMCDUMPPARTITION}
  fi
  mount -t ext3 -L /hmcdump /tmp/mnt
  mount -o loop /tmp/mnt/disk1.img /hmc/dump/hsc_install.images
else
  # Copy disk1.img from media over for performance and better reliability
  echo "Retrieving image..."
  tar cf - /media/cdrom/images/disk1.img 2>/dev/null | tar -C /hmc/dump/cdrom/ -xBf - --checkpoint=20000 --checkpoint-action=exec="echo Retrieving image..." --strip-components=3
  if [ $? -eq 0 -a -e /hmc/dump/cdrom/disk1.img ]; then
    mount -o loop /hmc/dump/cdrom/disk1.img /hmc/dump/hsc_install.images
  else
    echo "Failed to retrieve image from media..."
    exit 10
  fi
fi

mount -t proc proc /hmc/proc
mount --bind /dev /hmc/dev
mount --bind /sys /hmc/sys

# setup grub2 usage
updategrub2
echo "GRUB2 Configured"

# if getHDName doesn't return the same value as getHDName 1, then
# the mpio is enabled.
if [ "$(/opt/hmc/bin/getHDName)" != "$(/opt/hmc/bin/getHDName 1)" ]; then
  enableMultipathBoot
fi

# nee to bring up lo network and localhost hostname
# for MOF compiler to work ....
ip link set lo up
chroot /hmc hostname localhost

chroot /hmc /opt/hsc/bin/applyUpdates install /dump/hsc_install.images
retcode=$?
rc=0
# Return code mapping in SetupWizardBean.java
if [ $retcode -ne 0 ]; then
  case $retcode in
  4) rc=44 ;;
  5) rc=45 ;;
# Until we can determine why applyUpdates return 6 ignore for now
#  6) rc=46 ;;
  7) rc=43 ;;
  *) ;;
  esac
fi
# Cleanup ip address in the eth0 network configuration file
# to avoid duplication with lo interface
sed -i "/^IPADDR/d" /hmc/etc/sysconfig/network-scripts/ifcfg-eth0

umount /hmc/sys
umount /hmc/dev
umount /hmc/proc
umount /hmc/dump/hsc_install.images
if [ "$MEDIA" == "disk" ]; then
  umount /tmp/mnt
fi
if [ "$MEDIA" = "media" ]; then
  rm -f /hmc/dump/cdrom/disk1.img
fi

RET_CODE=$rc
if [ $RET_CODE -eq 0 ]; then
  RESULT="Successful"
else
  RESULT="Failed"
fi
exit $RET_CODE
