#!/bin/sh
#
# init (from initrd image) - Boot Initialization
#
# This script is run _as_ init in the ramfs initrd root.
# It must exit with the real root filesystem mounted on /sysroot and no other
# filesystems mounted on the ramfs root filesystem. It is okay to have
# filesystems mounted below /sysroot as long as the system's init expects it.
#
# On exit this script performs a switch_root of /sysroot (so it will
# be moved to /) and the /sbin/init (within sysroot) is execed.

#-----------------------------------------------------------------------------
# set essential path and working directory
export PATH=/sbin:/bin:/usr/sbin:/usr/bin
export PS1="SLOS# "
export TERM=linux
# disk encryption stuff
KNAME=".keyfile"
KFILE="" # set if/when keyfile found
KPW=""   # set if/when key entered\
cd /
#-----------------------------------------------------------------------------
# create busybox links for common linux cmds
# this fixes issue where ash does not search $PATH when /proc is not mounted
cd bin
for cmd in $(/bin/busybox --list) ; do
   [ ! -e $cmd ] && /bin/busybox ln /bin/busybox $cmd
done
cd -

#-----------------------------------------------------------------------------
GOL=".init.log"
LOG="/$GOL"
#-----------------------------------------------------------------------------
# echo to screen and log to file
log() {
   D=$(date -Is)
   echo "$D:$*" >>$LOG
   echo "$*"
} # log

#-----------------------------------------------------------------------------
# move log file
mvlog() {
   NEW="$1/$GOL"
   /bin/cp  -f $LOG $NEW 2>/dev/null
   LOG="$NEW"
   log "mvlog: log moved to $LOG"
} # mvlog

#-----------------------------------------------------------------------------
# Pull in configuration telling us what is what
read_config() {

   if [ -f /boot.cnf ] ; then
      log "read_config: Loading boot configuration file /boot.cnf"
      . /boot.cnf
      cat /boot.cnf | tee -a $LOG
   else
      log "read_config: No boot configuration"
      modules=`cd /lib ; echo *.ko`
   fi
   # if /boot not specified in boot.cnf then assign default
   if [ -z ${boot_dev} ] ; then
       if [[ $root =~ "nvme" ]] ; then
           boot_dev=/dev/nvme0n1p1 
       else
           boot_dev=/dev/sda1
       fi
  fi
} # read_config

#-----------------------------------------------------------------------------
mount_sys() {
   log "mount_sys: Mounting usual system devices"
   # common file systems
    [ -d /dev ]       || mkdir -m 0755 /dev
    [ -d /root ]      || mkdir -m 0700 /root
    [ -d /proc ]      || mkdir -m 0755 /proc
    [ -d /sys ]      || mkdir -m 0755 /sys
    [ -d /sysroot ]  || mkdir -m 0755 /sysroot
    [ -d /tmp ]      || mkdir -m 1755 /tmp
    [ -d /run ]      || mkdir -m 0755 /run
    [ -d /var/lock ] || mkdir -p /var/lock

    mount -t proc -o nosuid,noexec,nodev proc /proc
    mount -t sysfs -o nosuid,noexec,nodev sys /sys
    mount -t tmpfs -o mode=0755,nosuid,nodev,strictatime tmpfs /run
    mount -t devtmpfs -o mode=0755,nosuid,strictatime devtmpfs /dev

    mkdir -m 0755 /dev/pts
    mount -t devpts -o gid=5,mode=620,noexec,nosuid devpts /dev/pts
    mkdir -m 0755 /dev/shm
    mount -t tmpfs -o mode=1777,nosuid,nodev,strictatime tmpfs /dev/shm

    [ ! -h /dev/fd ] && ln -s /proc/self/fd /dev/fd
    [ ! -h /dev/stdin ] && ln -s /proc/self/fd/0 /dev/stdin
    [ ! -h /dev/stdout ] && ln -s /proc/self/fd/1 /dev/stdout
    [ ! -h /dev/stderr ] && ln -s /proc/self/fd/2 /dev/stderr

    if [ -e /sys/firmware/efi ] ; then
        [ -e /sys/firmware/efi/efivars ] || mkdir -p /sys/firmware/efi/efivars
        mount -t efivarfs efivarfs /sys/firmware/efi/efivars
    fi
} # mount_sys

#-----------------------------------------------------------------------------
# create basic devices
make_devs() {
   # We need some devices for biosdevname to work properly
   log "make_devs: Make char devices"
   [ -c /dev/null ] || mknod -m 0666 /dev/null c 1 3
   [ -c /dev/ptmx ] || mknod -m 0666 /dev/ptmx c 5 2
   [ -c /dev/console ] || mknod -m 0600 /dev/console c 5 1
   [ -c /dev/kmsg ] || mknod -m 0660 /dev/kmsg c 1 11
   [ -c /dev/mem ] || mknod -m 0640 /dev/mem c 1 1
   sleep 1
} # make_devs
#-----------------------------------------------------------------------------
# Initialize FIPS RNG
#
init_rng() {
    dd status=none if=/dev/urandom of=/dev/null bs=1 count=1 2>/dev/null
} # init_rng
#-----------------------------------------------------------------------------
# tweak the entropy sources for LRNG
# 1) if set via kernel cmd line, use that value
# 2) if set in file /boot/.rdrand or /boot/.jitter, use that value
#    ^^^ avoid long file names in case /boot is fat filesystem
# 3) otherwise, use below default hardcoded value
init_lrng() {
   # kernel have LRNG?
   [ -d "/sys/module/lrng_archrandom" ] || return 0

   # set how much RDRAND to use for LRNG init
   F="/sys/module/lrng_archrandom/parameters/archrandom"
   G="/boot/.rdrand"
   if [ -z "$archrandom" ] ; then
      archrandom=64
      [ -f $G ] && archrandom="$(cat $G)"
   fi
   # set rdrand entropy value
   if [ -e "$F" ] ; then
      echo $archrandom >$F
      echo "LRNG:SLOS:lrng_archrandom.archrandom=$archrandom" >/dev/kmsg
   fi

   # set how much jitter to use for LRNG init
   F="/sys/module/lrng_jent/parameters/jitterrng"
   G="/boot/.jitter"
   if [ -z "$jitterrng" ] ; then
      jitterrng=64
      [ -f $G ] && jitterrng="$(cat $G)"
   fi
   # bump jitter entropy value
   if [ -e "$F" ] ; then
      echo $jitterrng >$F
      echo "LRNG:SLOS:lrng_jent.jitterrng=$jitterrng" >/dev/kmsg
   fi

} # init_lrng

#-----------------------------------------------------------------------------
# central function to fail to shell
failsh() {
   log "failsh: Dropping into a command shell."
   echo
   echo
   echo "        $*"
   echo "        Dropping into a command shell."
   echo
   echo
   /bin/sh

} # failsh

#-----------------------------------------------------------------------------
# Parse kernel command line
# parameters we look for:
# shell       - boot into a boot shell
# nomod       - do not load any kernel modules
# nomod=...   - do not load specific kernel module
# root=...    - (required) name of the root device
# fs=...      - name of lvm filesystem to setup
# ro          - mount filesys as R/O
# rw          - mount filesys as R/W (default)
# ext2        - mount root as type ext2
# ext3        - mount root as type ext3
# ext4        - mount root as type ext4 (default)
# xfs         - mount root as type xfs
# init=...    - specify different init than /sbin/init
# debuginit=0 - enable initrd debug features
# selinux=0   - do not setup selinux
# enforcing=0 - do not set enforcing mode (i.e. permissive)
# sesleep=x   - pause for x seconds (x>0) after selinux setup
parse_cmdlin() {
   loadmods=y
   init=/sbin/init
   debuginit=0
   selinux=0
   enforcing=0
   sesleep=0
   MNTOPTS=""
   MNTTYP="ext4"
   jitterrng=""
   archrandom=""

   log "parse_cmdlin: Parse kernel cmd line arguments"
   set - $(cat /proc/cmdline)
   for arg; do
      case $arg in
      shell)
         /bin/sh
         ;;
      nomod)
         loadmods=n
         ;;
      nomod=*)
         ignmods="$ignmods:${arg#nomod=}:"
         ;;
      root=*)
         eval $arg
         ;;
      rootfstype=*)
         eval $arg
         MNTTYPE=$rootfstype
         ;;
      fs=*)
         eval $arg
         ;;
      ro)
         MNTOPTS="-o ro"
         ;;
      rw)
         MNTOPTS=""
         ;;
      xfs)
         MNTTYP="xfs"
         ;;
      ext4)
         MNTTYP="ext4"
         ;;
      ext3)
         MNTTYP="ext3"
         ;;
      ext2)
         MNTTYP="ext2"
         ;;
      init=*)
         eval $arg
         ;;
      debuginit)
         debuginit=1
         ;;
      selinux=*)
         eval $arg
         ;;
      enforcing=*)
         eval $arg
         ;;
      sesleep=*)
         eval $arg
         ;;
      lrng_jent.jitterrng=*)
         eval ${arg##lrng_jent.}
         ;;
      lrng_archrandom.archrandom=*)
         eval ${arg##lrng_archrandom.}
         ;;
      esac
   done
   
   if [ -z "$root" ] ; then
      failsh "No root specified (on kernel command line or in boot.conf)."
      reboot -f
   fi

} # parse_cmdlin

#-----------------------------------------------------------------------------
# start udevd
#
start_udevd() {
    if [ -w /sys/kernel_uevent_helper ]; then
        echo > /sys/kernel/uevent_helper
    fi

    SYSTEMD_LOG_LEVEL=notice /usr/lib/systemd/systemd-udevd --daemon --resolve-names=never
    
    udevadm trigger --type=subsystems --action=add
    udevadm trigger --type=devices --action=add
    udevadm settle || true
    udevadm trigger --action=change --attr-match=dm/name

    udevadm trigger --type=devices --action=add 2>/dev/null
    udevadm trigger --action=change --attr-match=dm/name 2>/dev/null
    udevadm control --exit 2>/dev/null
}

#-----------------------------------------------------------------------------
# install a module that exits and is not in $ignmods
install_module() {
   #install module
   echo "install_module: loading $1 ..." >> /run/modules.log
   modprobe $1 >> /run/modules.log 2>&1
} # install_module

#-----------------------------------------------------------------------------
# search and install all network related kernel modules
install_netmods() {
   log "install_netmods: Parse kernel cmd line arguments"
   echo /bin/mdev >/proc/sys/kernel/hotplug
   mkdir -p /lib
   ln -s /sysroot/lib/firmware /lib/firmware
   ln -s /sysroot/lib/modules  /lib/modules
   k=$(uname -r)
   l=/sysroot/lib/modules/$k
   if [ -f $l/modules.dep ] ; then
      cat $l/modules.dep | \
         while read m ; do
         f=${m%:*}
         if echo "$f" | egrep -q '(kernel/drivers/net/(ethernet|virtio|vmxnet)|extra/hv_netvsc.ko)'; then
            log "install_netmods: Loading $(basename $f)..."
            modprobe $l/$f >>$LOG 2>&1
         fi
      done
   else
      log "Not found: $l/modules.dep"
   fi

   log "Allow new devices to settle..."
   sleep 3

   # Debug
   #    for i in 1 2 3 4 5 6 ; do
   #      echo "ls -l /sys/class/net/"
   #      ls -l /sys/class/net/
   #      echo "ls -l /sys/class/net/eth0"
   #      ls -l /sys/class/net/eth0
   #      echo "sleep 3"
   #      sleep 3
   #      echo ; echo
   #   done

} # install_netmods

#-----------------------------------------------------------------------------
# install kernel modules if loadmods=y and the modules are not in ignmods
load_mods() {
   for mod in $modules ; do
      install_module $mod
   done
   log "allow devices to settle."
   sleep 3
} # load_mods

md_init() {
    if [ -s /etc/mdadm.conf ]; then
        /bin/mdadm -q --assemble --scan --no-degraded || true
        udevadm settle || true
    fi
} # md_init

#-----------------------------------------------------------------------------
# kludge for HP Blade storage driver
hp_blade() {
   if [ -n "$(ls /dev/cciss!* 2>/dev/null)" ]; then
      mkdir -p /dev/cciss
      for d in /dev/cciss!*; do
         s=${d#/dev/cciss!}
         cp -a $d /dev/cciss/$s
      done
   fi

} # hp_blade

#-----------------------------------------------------------------------------
# Run optional /etc/rc.local
rc_local() {
   if [ -f /etc/rc.local ] ; then
      log "Local Boot Initialization"
      . /etc/rc.local
   fi
} # rc_local

#-----------------------------------------------------------------------------
# wait for entropy pool to fill
entropy_wait() {
   # kernel have LRNG?
   if [ -d "/sys/module/lrng_archrandom" ] ; then
      M="LRNG fully seeded" # search dmesg for this msg
   else
      M="crng init done" # search dmesg for this msg
   fi
   rc=1
   [ -n "$1" ] && T="$1" || T="60" # timeout, max seconds to wait
   F="/tmp/entropy_wait.tmp" # tmp file to hold dmesg log
   S="$(date '+%s')" # start   time
   C="$S"            # current time
   E="$((C-S))"      # elapsed time
   N="$((1*256*1024))" # number of reads
   G=""              # dmesg about LRNG
   L=1               # count loops
   log "entropy_wait: begin"
   # loop waiting
   while (true) ; do
      # LRNG fully seeded?
      dmesg >$F
      G=$(grep "$M" $F)
      if [ -n "$G" ] ; then
         rc=0
         log "entropy_wait:$G"
         break
      fi
      log "entropy_wait:try $L, elapsed: $E sec, read $N blocks" # logging creates entropy
      # using files creates entropy
      busybox dd if=/dev/sda of=/dev/null bs=1024 count=$N skip=$((L*N)) &>/dev/null
      C="$(date '+%s')"      # current time
      E2="$E"                # prev elapsed time
      E="$((C-S))"           # elapsed time
      E3="$((E-E2))"         # this loop time
      [ $E3 -lt 1 ] && N="$((N*2))" # loop < 1sec? double count.
      [ $E -ge $T ] && break # elapsed time greater than timeout?
      L="$((L+1))"
   done
   sleep 1
   rm -f $F
   # show result
   [ $rc -eq 0 ] && log "entropy_wait: end, success."
   [ $rc -ne 0 ] && log "entropy_wait: end, fail, timeout."
   # show lrng settings
   AR="$(cat /sys/module/lrng_archrandom/parameters/archrandom)"
   JE="$(cat /sys/module/lrng_jent/parameters/jitterrng)"
   log "LRNG:SLOS:lrng_jent.jitterrng=$JE,lrng_archrandom.archrandom=$AR"

   return $rc
} # entropy_wait

#-----------------------------------------------------------------------------
# get block device size in MB. input: hw=blk-dev output: siz=size in MB
# do not echo anything to stdout! that would mess up list_usb output
get_blk_siz() {
   siz=0
   if [ ! -e $hw/size ] ; then 
      echo "$hw has no size. skip." | tee -a $LOG
   else
      siz=$(cat $hw/size) # device size in sectors
   fi
   [ -z "$siz" ]  && siz=0
   [ $siz -gt 0 ] && siz=$((siz/2))    # convert sectors to KB
   [ $siz -gt 0 ] && siz=$((siz/1024)) # convert KB to MB
   [ $siz -gt 0 ] && echo "$hw size $siz MB $((siz/1024)) GB" | tee -a $LOG
} # get_blk_siz

#-----------------------------------------------------------------------------
# Get block device removable flag. input: hw=blk-dev output: rem=0 or 1
# do not echo anything to stdout! that would mess up list_usb output
get_blk_rem() {
   # if not removable drive, loop again
   rem="0"
   if [ -e "$hw/removable" ] ; then 
       rem=$(cat $hw/removable)
   fi
   [ -z "$rem" ] && rem="0"
   echo "$hw removable = $rem" | tee -a $LOG
} # get_blk_rem

#-----------------------------------------------------------------------------
# echo a list of usb thumb-drive partitions, e.g. /dev/sdb1 
# do not echo anything to stdout! that would mess up list_usb output
list_usb() {

    # min/max USB siz in MB (differentiate between thumb drive VS hard drive)
    USBmin=32            #  32 MB
    USBmax=$((128*1024)) # 128 GB

    mdev -s                 # Populate /dev with the known devices
    blkid >/tmp/blkid.txt   # get list of partitioned block devices
    # step thru sda sdb sdc ...
    for hw in /sys/class/block/sd[a-z] ; do

        # not removable? don't use.
        get_blk_rem
        if [ "$rem" != "1" ] ; then
           echo "$hw not removable. skip." | tee -a $LOG
           continue
        fi

        # not within usb size? don't use.
        get_blk_siz
        if [ $siz -lt $USBmin ] || [ $siz -gt $USBmax ] ; then
           echo "$hw not within size. skip." | tee -a $LOG
           continue
        fi

        # we only store key on first usb partition, e.g. sda1
        A="$(basename $hw)"  # e.g. "sda"
        B="${A}1"            # e.g. "sda1"
        if [ ! -e "$hw/$B" ] ; then
           echo "$hw/$B not found. skip." | tee -a $LOG
           continue
        fi

        # double check its a good device
        if ! grep -q "^/dev/$B" /tmp/blkid.txt ; then
           echo "/dev/$B not found in blkid. skip." | tee -a $LOG
           continue
        fi

        # we found a good one, e.g. "/dev/sda1"
        echo "/dev/$B is good." | tee -a $LOG
        echo "/dev/$B"

    done # hw

    return
} # list_usb

#-----------------------------------------------------------------------------
# one try to mount usb and read key
read_key_usb_try() {
   rc=1

   # get list of suspected usb thumb drives
   usblist=$(list_usb)
   [ -z "$usblist" ] && return $rc

   # check each usb device until we find keyfile
   for dev in $usblist ; do

      # mount usb dev
      log "read_key_usb: probing $dev"
      mount "$dev" /usb 2>/dev/null
      if [ $? -ne 0 ] ; then
         log "read_key_usb: failed to mount $dev"
         continue
      fi

      # found keyfile? leave usb mounted
      if [ -f /usb/.keyfile ] ; then
         rc=0
         KFILE=/usb/.keyfile
         log "read_key_usb: Keyfile found on usb: $dev"
         sleep 1
         break

      # this is not it, umount and try next
      else
         log "read_key_usb: no key found on $dev"
         umount /usb
      fi

   done

   return $rc
} # read_key_usb_try

#-----------------------------------------------------------------------------
# look for key on usb, allow user to plug-in the drive if not found
read_key_usb() {
   rc=1
   log "read_key_usb: read key from usb device"
   # usb partition mount point
   [ -d /usb ] || mkdir /usb

   C=0
   while [ $C -le 3 ] ; do
      C=$((C+1))
      read_key_usb_try
      if [ $rc -eq 0 ] ; then 
         break
      else
         log "Not Found: USB drive containing disk encyption key."
         log "Plug in USB drive containing key, and press [enter]"
         read A
         sleep 5
      fi
   done

   # for later use: if dir /usb exists, then usb is mounted, and keyfile exists
   if [ $rc -ne 0 ] ; then
      rmdir /usb
      log "Too many attempts to find key on USB. Quit."
   fi

   return $rc
} # read_key_usb

#-----------------------------------------------------------------------------
# prompt user to enter the passphrase, save in var KPW
read_key_user() {
   rc=0
   log "read_key_user: read key from console"
   read -p "Enter Disk Encryption Password: " -s KPW
   return $rc
} # read_key_user

#-----------------------------------------------------------------------------
# unlock one encrypted partition using passphrase string in KPW
unlock_enc_one_pass() {
   rc=0
   count=0
   log "unlock_enc_one_pass: unlock an encrypted partition"

   # we previously entered the key, but if it fails, ask again
   while [ $count -lt 3 ] ; do
      log  "[pass] -> cryptsetup -q luksOpen  $partname $encdisk"
      echo "$KPW" | cryptsetup -q luksOpen  "$partname" "$encdisk"
      rc=$?
      [ $rc -eq 0 ] && break
      # failed? read p/w from console again
      KPW=""
      echo "unlock_enc_one_pass: That Password did not unlock the disk."
      read_key_user # read pass from console again
      count=$((count+1))
   done

   # if we can't get the key, time to fail
   if [ $rc -ne 0 ] ; then
      failsh "unlock_enc_one_pass: Too many failed attempts. Cannot boot."
   fi

   return $rc
} # unlock_enc_one_pass

#-----------------------------------------------------------------------------
# unlock one encrypted partition using key file KFILE (from disk or usb drive)
unlock_enc_one_file() {
   rc=0
   log "unlock_enc_one_file: unlock an encrypted partition"
   log "cryptsetup -d $KFILE luksOpen $partname $encdisk"
   cryptsetup -d $KFILE luksOpen $partname $encdisk
   rc=$?

   if [ $rc -ne 0 ] ; then
      log "unlock_enc_one_file: luksOpen file failed $rc part=$partname disk=$encdisk"
      sleep 5
   fi

   return $rc
} # unlock_enc_one_disk

#-----------------------------------------------------------------------------
# unlock one encrypted partition
unlock_enc_one() {
   rc=0
   encdisk="$1"
   partname="$2"
   options="$3"
   log "unlock_enc_one: encdisk=$1 partname=$2 options=$3 root=$root"
  
   # verify partition is a valid block device
   if [ ! -b "$partname" ] ; then
      rc=1
      log "unlock_enc_one: Not a block device: $partname"
      sleep 5
   fi

   # verify partition is encrypted
   if [ $rc -eq 0 ] ; then
      cryptsetup -v isLuks $partname
      rc=$?
      if [ $rc -ne 0 ] ; then
         log "unlock_enc_one: $partname not encrypted"
         sleep 5
      fi
   fi

   # so far, so good
   if [ $rc -eq 0 ] ; then

   # If key is stored in file
   if [ -n "$KFILE" ] ; then
      unlock_enc_one_file
   # If key is provided as string (passphrase)
   elif [ -n "$KPW" ] ; then
      unlock_enc_one_pass
   fi

   # save root encdisk name for later
   if [ "$encdisk" == "$(basename $root)" ] ; then
      log "unlock_enc_one: Found root: part=$partname disk=$encdisk"
   fi

   fi # so far, so good

   log "unlock_enc_one: returning $rc"
   return $rc
} # unlock_enc_one

#-----------------------------------------------------------------------------
# unlock all encrypted partitions listed in .crypttab file
unlock_enc_all() {
   rc=0
   log "unlock_enc_all: unlock all parititons"

   # some setup
   mkdir -p /run/cryptsetup
   mkdir -p /etc/cryptsetup-initramfs
   echo "CRYPTSETUP=y" >/etc/cryptsetup-initramfs/conf-hook

   # unlock each encrypted partition listed in .crypttab
   while read L ; do
      if [ -n "$L" ] && [ "${L:0:1}" != "#" ] ; then
         unlock_enc_one $L
         rc=$?
         if [ $rc -ne 0 ] ; then
            log "unlock_enc_all: exit loop, $rc"
            sleep 5
         fi
      fi
   done < /boot/.crypttab
   log "unlock_enc_all: returning $rc"
   return $rc
} # unlock_enc_all

#-----------------------------------------------------------------------------
# look for keyfile on /boot
read_key_disk() {
   rc=1
   log "read_key_disk:read key from disk"

   # if /boot dir exists, then it is mounted
   if [ -d /boot ] ; then
      # verify /boot has needed files
      if [ -f /boot/.crypttab ] && [ -f /boot/$KNAME ] ; then
         rc=0
         KFILE=/boot/$KNAME
         log "read_key_disk:found keyfile"
      else
         log "read_key_disk:no keyfile found"
         sleep 5
      fi
   else
      log "read_key_disk:/boot not mounted"
   fi

   return $rc
} # read_key_disk

#-----------------------------------------------------------------------------
# we have the key, now mount encrypted root
mount_enc_root() {
   rc=1
   if [ ! -b "$rootdev" ] ; then
      log "mount_enc_root:ERROR: $rootdev not a block device"
   else
      log "mount_try $rootdev /sysroot"
      mount_try $rootdev /sysroot
      rc=$?
      if [ $rc -ne 0 ] ; then
         log "mount_enc_root:ERROR: Failed to mount: $rootdev /sysroot"
         sleep
      fi
   fi
   return $rc
} # mount_enc_root

#-----------------------------------------------------------------------------
# try to mount encrypted dev "$1" on dir "$2"
mount_enc() {
   rc=1
   dev="$1"
   dir="$2"
   log "mount_enc: mount an encrypted partition"

   # In SLOS a /boot partition is _required_ for encrypted disks
   if [ ! -d /boot ] ; then
      log "mount_enc:/boot not found, required for encrypted disk."
      return 1
   fi

   # the key maybe in different places, but these files live on /boot
   if [ ! -f /boot/.cryptsrc ] || [ ! -f /boot/.crypttab ] ; then
      log "mount_enc:cryptsrc crypttab not found, required for encrypted disk."
      sleep 5
      return 1
   fi

   # this tells us where is the key
   Csrc=$(cat /boot/.cryptsrc)
   log "mount_enc: keyfile source: $Csrc"

   # look for keyfile on /boot
   if [ "$Csrc" == "disk" ] ; then
      read_key_disk
      rc=$?
   # look for keyfile on USB
   elif [ "$Csrc" == "usb" ] ; then
      read_key_usb
      rc=$?
   # ask user to enter the key
   elif [ "$Csrc" == "pw" ] ; then
      read_key_user
      rc=$?
   fi

   # no keyfile found. we're done.
   if [ $rc -ne 0 ] ; then
      log "mount_enc: no key found."
      sleep 3
      return $rc
   fi

   # we got the key, now unlock all encrypted partitons
   unlock_enc_all
   rc=$?
   if [ $rc -ne 0 ] ; then
      log "mount_enc: unlock_enc_all returned error, $rc"
      sleep 5
   fi

   # partitions unlocked, now mount encrypted root
   if [ $rc -eq 0 ] ; then
      mount_enc_root 
      rc=$?
      if [ $rc -ne 0 ] ; then
         log "mount_enc: mount_enc_root returned error, $rc"
         sleep 5
      fi
   fi

   [ $rc -eq 0 ] && log "mount_enc:end: success"
   return $rc
} # mount_enc

#-----------------------------------------------------------------------------
# try to mount dev "$1" on dir "$2" using several partition types
# return rc=0 if success
mount_try() {
   rc=0
   dev="$1"
   dir="$2"
   log "mount_try:begin: mount $dev $dir"

   if ! mount $MNTOPTS         $dev $dir 2>/dev/null ; then  ## 1
       echo "1.failed mount $MNTOPTS         $dev $dir"; sleep 1
   if ! mount $MNTOPTS -t ext4 $dev $dir 2>/dev/null ; then  ## 2
       echo "2.failed mount $MNTOPTS -t ext4 $dev $dir"; sleep 1
   if ! mount $MNTOPTS -t xfs  $dev $dir 2>/dev/null ; then  ## 3
       echo "3.failed  mount $MNTOPTS -t xfs  $dev $dir"; sleep 1
   if ! mount                  $dev $dir 2>/dev/null ; then  ## 4
       echo "4.mount without opts $dev $dir "; sleep 1
      # mount without OPTS above required for Hyper-V/Azure
      rc=1
      log "mount_try:failed all attempts"
   fi # 4
   fi # 3
   fi # 2
   fi # 1

   [ $rc -eq 0 ] && log "mount_try:end: success"
   return $rc
} # mount_try

#-----------------------------------------------------------------------------
# start LVM if needed (root is not a native block device)
start_lvm() {
   #log "1. start_lvm:find LVM devices"
   # if root is not a physical device, then start LVM drivers
   if [ -n "$fs" -o ! -d  /sys/class/block/${root#/dev/} ] \
      && [ "${root#/dev/cciss}" == "$root" ] \
      && [ -x /bin/lvm ] ; then
         # start LVM
         #log "2. Inside lvm start_lvm: starting LVM."
     /bin/lvm vgmknodes
     sleep 3
         /bin/lvm vgscan --ignorelockingfailure
     sleep 3
         /bin/lvm vgchange -ay --ignorelockingfailure $fs
     sleep 3
     /bin/lvm vgmknodes
     sleep .5
   fi
   #echo root is  $root; ls -l $root; sleep 1
   if [ -b $root ] && [[ $root =~ "md" ]] ; then
         #log "3. start_lvm: starting LVM."
     #ls -l /dev/mapper/
     #echo 4. /bin/lvm vgmknodes
     /bin/lvm vgmknodes ; sleep 2
         #echo 5. /bin/lvm vgchange -a y --ignorelockingfailure $fs
         /bin/lvm vgchange -a y --ignorelockingfailure $fs & sleep 2
     sleep 2
         #echo 5.5 /bin/lvm vgchange -a y
         /bin/lvm vgchange -a y & sleep 1 
     sleep 2
         #echo 6. /bin/lvm pvscan vgscan lvscan
         /bin/lvm pvscan & sleep 2
     sleep 3
         /bin/lvm vgscan & sleep 2
     sleep 2
         /bin/lvm lvscan & sleep 2
     #ls -l /dev/mapper/
     sleep 3
     #echo 7. Killing vgscan
     /bin/busybox kill -9 `/bin/busybox pgrep lvm ` 2>/dev/null
     sleep .1
    fi
} # start_lvm

#-----------------------------------------------------------------------------
# mount root filesystem
mount_root() {
   rc=1

   # if /sysroot already mounted, then nothing to do
   if [ $(stat -c "%d" /) != $(stat -c "%d" /sysroot/.) ]  ; then
      log "mount_root: $rootdir was already mounted."
      return 0
   fi

   # if root is on a md device, start the device
   if [ -f /etc/mdadm.conf ]; then
       /bin/mdadm -q --assemble --scan --no-degraded || true
       udevadm settle || true
   fi

    
# Start LVM always
start_lvm

### Notes for Disk Encryption
# first see wiki page: https://us.slos.int.shn.io/wiki/Encrypted
# 1) To customize and provide the key as a string:
#    1a) Put "pw" in /boot/.cryptsrc 
#    1b) Edit read_key_user() above in this file, to fetch the key by 
#        your custom method, and place it as a string in $KPW
# 2) To customize and provide the key as a file:
#    2a) Put "disk" in /boot/.cryptsrc
#    2b) Edit read_key_disk() above in this file, to find/create the 
#        key file by your custom method, and place pathname in $KFILE

   # this is a place where we could add a root name transform
   # but this really is not needed, as long as .crypttab list the devices
   if [ $rc -ne 0 ] ; then
      rootdev="$root"
      log "rootdev == $rootdev"
   fi

   # try to mount root various methods
   if [ $rc -ne 0 ] ; then
      mount_try $rootdev /sysroot
      rc=$?
   fi

   # try to mount root as encrypted partition
   if [ $rc -ne 0 ] ; then
      mount_enc $rootdev /sysroot
      rc=$?
   fi

   if [ $rc -ne 0 ] ; then
      failsh "mount_root: Failed to mount the root filesystem xfs/ext4 : $rootdev"
   fi
   sleep 1
   return $rc
} # mount_root

#-----------------------------------------------------------------------------
# try to mount boot on /boot in the initrd tmpfs
# for later scripts: if dir /boot exists, then boot is mounted on it.
mount_boot() {
   rc=1
   # was this was already done?
   grep -q "/boot" /proc/mounts && return 0

   # mount R/W so we may store the init.log there
   log "mount_boot:try mount $boot_dev [tmpfs]/boot"
   mkdir -p /boot
   if   mount -t ext2 -o rw $boot_dev /boot 2>/dev/null ; then
      rc=0
      log "mount_boot:mounted: ext2 $boot_dev [tmpfs]/boot"
   elif mount -t vfat -o rw $boot_dev /boot 2>/dev/null ; then
      rc=0
      log "mount_boot:mounted: vfat $boot_dev [tmpfs]/boot"
   else
      rmdir /boot
      log "mount_boot:no boot partition found."
   fi

   # succeed? log the mount entry and display to user
   if [ $rc -eq 0 ] ; then
      mvlog /boot   # move log to /boot for permanence
   fi

   sleep .5
   return $rc
} # mount_boot

#-----------------------------------------------------------------------------
# Not required: the mount will be handled by systemd.
mount_all_disks () {
    if [ -f /sysroot/etc/fstab ]; then
        cat /sysroot/etc/fstab | egrep -vw "/boot|/|^[ ,    ]*#" | sort -f >/tmp/newfstab
        while read _d _m _t _o _r; do
            rc=0
            [ -d /sysroot/$_m ] || mkdir -p  /sysroot$_m
            ( [ "$_t" == "swap" ] && /bin/busybox mkswap $_d && /bin/busybox swapon $_d ) 2>/dev/null || rc=1
            [ $rc == 1 ] && mount -t $_t -o $_o $_d /sysroot/$_m 2>/dev/null
            mount -t $_t -o $_o $_d /sysroot/$_m 2>/dev/null
        sleep .1
        done < /tmp/newfstab
    fi
} # mount_all_disks

#-----------------------------------------------------------------------------
# mount /etc,/usr,/lib on /sysroot if they are needed and live on different file sys
# Entry: "$other" should be list of dirs to be mounted, "/etc /usr /lib" etc.
mount_other() {
   log "mount_other: mount any paritions, in addition to root, needed for boot."
   # if we have other filesys to mount, then pause for root to settle
   [ -n "$other" ] && sleep 5
   fd="" # device, e.g. /dev/fs/etc
   fm="" # mount point, /etc
   # mount any other needed file systems (/etc, /usr, /lib)
   for f in $other ; do
      [ -z "$fd" ] && fd="$f" && continue
      [ -z "$fm" ] && fm="$f"
      [ -d /sysroot$fm ] || mkdir -p  /sysroot$fm
      # perform file system check, only if needed
      #do_fsck $fd # not needed, systemd will perform fsck during system boot
      # try to mount
      #log  "mount $MNTOPTS -t $MNTTYP $fd /sysroot$fm"
      if !  mount $MNTOPTS -t $MNTTYP $fd /sysroot$fm 2>/dev/null; then
         # if first try failed, pause and retry once more
         sleep 5
         if !  mount $MNTOPTS -t $MNTTYP $fd /sysroot$fm 2>/dev/null; then
            failsh "mount_other: Failed to mount filesystem: $fm"
         fi
      fi
      fd=""; fm="";
   done

} # mount_other

#-----------------------------------------------------------------------------
# Start selinux unless specified differently on kernel command line
# NOTE: If this doesn't work, then the partitions maybe mounted r/o.
start_selinux() {
    NEWROOT="/sysroot"
    log "start_selinux: begin"

    [ "x$selinux" == "x0" ] && return 0
    permissive=0
    SELINUX="enforcing"
    [ -e "$NEWROOT/etc/selinux/config" ] && . "$NEWROOT/etc/selinux/config"

    [ "$SELINUX" == "disabled" ] && return 0

    # Attempt to load SELinux Policy
    if [ -x "$NEWROOT/usr/sbin/load_policy" -o -x "$NEWROOT/sbin/load_policy" ]; then
        local ret=0
        log "start_selinux: Loading SELinux policy"
        mount -o bind /sys $NEWROOT/sys
        # load_policy does mount /proc and /sys/fs/selinux in
        # libselinux,selinux_init_load_policy()
        if [ -x "$NEWROOT/sbin/load_policy" ]; then
            LANG=C chroot "$NEWROOT" /sbin/load_policy -i
            ret=$?
        else
            LANG=C chroot "$NEWROOT" /usr/sbin/load_policy -i
            ret=$?
        fi

        if [ $ret -eq 0 -o $ret -eq 2 ]; then
            # If machine requires a relabel, force to permissive mode
            log "start_selinux: Machine requires a relabel, force to permissive mode"
            [ -e "$NEWROOT"/.autorelabel ] && echo 0 > /sysroot/sys/fs/selinux/enforce
            mount --rbind /dev "$NEWROOT/dev"
            LANG=C chroot "$NEWROOT" /sbin/restorecon -R /dev
            return 0
        fi

        if [ $ret -eq 3 -o $permissive -eq 0 ]; then
            failsh "start_selinux: Machine in enforcing mode.  Not continuing"
        fi
        return 0
    elif [ $permissive -eq 0 -a "$SELINUX" != "disabled" ]; then
        failsh "start_selinux: Machine in enforcing mode and cannot execute load_policy." \
               "To disable selinux, add selinux=0 to the kernel command line." \
               "Not continuing"
    fi
    # pause to read console
    if [ $sesleep -gt 0 ] ; then
        log "start_selinux: ** SELinux sleep for $sesleep seconds."
        sleep $sesleep
    fi
} # start_selinux

#-----------------------------------------------------------------------------
# switch root to /sysroot
#
switch_root() {

   # unmount boot from tmpfs mount
   [ -d /boot ] && umount /boot && rmdir /boot
   [ -d /usb  ] && umount /usb  && rmdir /usb

   # find switch_root, different for busybox versus full system.
   if   [ -f /bin/switch_root  ] ; then SR=/bin/switch_root
   elif [ -f /sbin/switch_root ] ; then SR=/sbin/switch_root
   else                            failsh "HELP! No switch_root found!" 
   fi

   mkdir -p /sysroot/dev
   mount -n -o move /dev/ /sysroot/dev || mount -n --move /dev /sysroot/dev
   sleep 3

   # switch to system root - this is the end of the initrd image
   log "Switching to new root and running init."
   exec $SR /sysroot $init

} # switch_root

#-----------------------------------------------------------------------------
# MAIN
#-----------------------------------------------------------------------------

read_config   # read initrd boot.cfg
init_rng      # initialize rng
mount_sys     # mount basic file systems
make_devs     # create basic devices
parse_cmdlin  # parse kernel cmd line
load_mods     # load kernel modules specified in config
mdev -s       # Populate /dev with the known devices
md_init
hp_blade      # fix up blade NIC devices
# Veer : Commenting the entropy_wait and init_lrng
#entropy_wait  # wait for RNG to be fully seeded
mount_boot    # mount boot on /boot
## init_lrng  # pass params to LRNG ## this no longer makes sense
rc_local      # Run optional /etc/rc.local
              log "1.mount_root starting"; sleep .1
mount_root    # mount root fs on /sysroot
#              log "2.start_selinux starting"; sleep .1
mount_all_disks
mount_other   # mount /etc,/usr,/lib on /sysroot if needed
sleep .1
#start_selinux # start selinux
              log "switch_root starting" ; sleep .1
#Udev is not available in busybox, disabling
start_udevd   # run udev
switch_root   # switch root and run system init

