#!/bin/sh
# /sbin/mkinitrd
# 
# NOTE: If called from a kernel RPM install (i.e. %post)
# then this is the rpm-post order:
# new-kernel-pkg -> kernutil -> mkinitrd

# NOTE: This will always make an initrd image. 
# In theory, if not using LVM (device-mapper) then we do not an initrd.
# But there are many situations that we can not know for sure.
# So we always make an initrd, unless --noinitrd is given.
INITRD_DIR=
LIST_CMD=no
FSTAB=/etc/fstab
NEED_MAPPER=yes
INITRD_FIL=
PROTO=/usr/lib/initrd
VERSION=$(uname -r)
KLIBDIR=
COMMANDS=
TMPDIR=/tmp

EC_CRYPT=no
ROOT_DEV=
ROOT_UUID=
ROOT_LABEL=
BOOT_DEV=/dev/sda
CRYPT_DEV=encroot

DUMP_DEV=
DUMP_FS=
KDUMP_CAPTURE=

#--------------------------------------------------------------------------------
# abstract messages
#--------------------------------------------------------------------------------
error() {
   echo "$@" 1>&2
}

log() {
   echo "$@"
}

#--------------------------------------------------------------------------------
# print help and exit
#--------------------------------------------------------------------------------
usage()
{
   error "Usage: mkinitrd [options]"
   error "options:"

   error "  --add <module>         Add the specified kernel module to initrd image"
   error "  --del <module>         Remove the specified kernel module from initrd image"
   error "  --fresh                Make a fresh initrd.img"
   error "  --fstab <fstab-file>   Use <fstab-file> instead of /etc/fstab"
   error "  --help                 Print this listing"
   error "  --initrd <img>         Name of existing initrd to start from"
   error "  --klib <dir>           Directory to look for kernel modules"
   error "  --list                 List modules in the initrd image"
   error "  --crypt                use encrypted root partition"
   error "  --noinitrd             Do nothing and exit with success code."
   error "  --output <img>         Where to write the initrd"
   error "  --proto <dir>          Name of proto directory to use"
   error "  --tmpdir <dir>         Temporary directory other than $TMPDIR"
   error "  --version <version>    Use specified kernel version from /lib/modules/"
   error "                            or specify \"latest\" for most recent install kernel,"
   error "                            or specify \"running\" for currently running kernel,"
   error "                            otherwise defaults to the running kernel."
   error "  --dump-dev <device>    Device file to use for dump"
   error "  --dump-fs <filesystem> Filesystem to mount for dump"

   exit ${1:-1}
}

#--------------------------------------------------------------------------------
# parse command line args
#--------------------------------------------------------------------------------
parse_args() {

   # Hack to recognize mkinitrd being called from a kernel RPM install.
   # We don't have to do anything because the RPM will also call new-kernel-pkg.
   if [ "$1" == "--allow-missing" ] ; then
      exit 0
   fi

   # parse each cmd line arg
   while [ $# -gt 0 ] ; do

   case $1 in
   --add)  if [ $# -lt 2 ] ; then usage 1; fi
      for m in $2 ; do
         COMMANDS="$COMMANDS +$m"
      done
      shift;;
   --del) if [ $# -lt 2 ] ; then usage 1; fi
      for m in $2 ; do
         COMMANDS="$COMMANDS -$m"
      done
      shift;;
   --klib) if [ $# -lt 2 ] ; then usage 1; fi
      KLIBDIR=$2
      shift;;
   --fstab) if [ $# -lt 2 ] ; then usage 1; fi
      FSTAB=$2
      shift;;
   --version) if [ $# -lt 2 ] ; then usage 1; fi
      VERSION=$2
      shift;;
   --initrd) if [ $# -lt 2 ] ; then usage 1; fi
      INITRD_FIL=$2
      shift;;
   --noinitrd)
      exit 0;;
   --output)
      # same as --initrd for output.
      INITRD_FIL=$2
      shift;;
   --proto) if [ $# -lt 2 ] ; then usage 1; fi
      PROTO=$2
      shift;;
   --tmpdir) if [ $# -lt 2 ] ; then usage 1; fi
      TMPDIR=$2
      shift;;
   --fresh)
      # does nothing. we always make fresh initrd.
      ;;
   --force)
      # does nothing. we always mkinitrd.
      ;;
   --list)
      LIST_CMD=yes
      ;;
   --crypt)
      EC_CRYPT=yes
      ;;
   --root)
      ROOT_DEV=$2
      shift;;
   --dump-dev)
      DUMP_DEV=$2
      shift;;
   --dump-fs)
      DUMP_FS=$2
      shift;;
   --help)
      usage 0
      ;;
   *)
      usage;;
   esac
   shift

   done # while

   # encrypted filesystem?
   [ -f /.cryptsrc ] && EC_CRYPT=yes

} # parse_args

#--------------------------------------------------------------------------------
# get block device type: normal or device-mapper
#--------------------------------------------------------------------------------
getdevtype() {
   if [ -e $1 ] ; then
      awk '$1 == "Block" { BLOCK=1 } BLOCK == 1 { printf("%s %s\n", $1, $2); }' /proc/devices |
      grep "^$((0x$(stat -L -c %t $1))) " |
      awk '{ print $2 }'
   else
      #
      # When the installer installed the kernel packet on an LVM
      # the device link will not exist on the target filesystem yet.
      # This is of the form /dev/[vol]/[vol]-root, e.g. /dev/fs/fs-root
      #
      # We make a guess if the root device is LVM based on the name.
      #
      # So we fall through to here. Almost certainly if the root
      # device path is 3 directories deep then we are using LVM.
      #
      case $1 in
      /dev/*/*)
         echo device-mapper 
         ;;
      *)
         echo unknown
         ;;
      esac
   fi
} # getdevtype

#--------------------------------------------------------------------------------
# get block device name of uuid
#--------------------------------------------------------------------------------
locate_uuid() {
   local myuuid=$1
   lsblk -l -no NAME,UUID | \
   while read name uuid ; do
      if [ "$myuuid" = "$uuid" ]; then
         echo "/dev/$name"
         break
      fi
   done
} # locate_uuid

#--------------------------------------------------------------------------------
# get block device name of LABEL
#--------------------------------------------------------------------------------
locate_label() {
   local mylabel=$1
   lsblk -l -no NAME,LABEL | \
   while read name label ; do
      if [ "$mylabel" = "$label" ]; then
         echo "/dev/$name"
         break
      fi
   done
} # locate_label

#--------------------------------------------------------------------------------
# calculate any missing args
#--------------------------------------------------------------------------------
deduce_args() {
   
   # Validate version
   if   [ "$VERSION" == "latest" ] ; then
       VERSION=$(/bin/ls -1tr /lib/modules/ | tail -1)
   elif [ "$VERSION" == "running" ] ; then
       VERSION=$(/bin/uname -r)
   fi
   if [ -z "$VERSION" ] || [ ! -d /lib/modules/$VERSION ] ; then
      error "Given --version is bad. Not found: /lib/modules/$VERSION"
      exit 1
   fi

   # Validate the proto dir
   if [ ! -d $PROTO ] ; then
      error "$PROTO: no such directory"
      exit 1
   fi

   # binaries to include in initrd
   BINARIES="/sbin/busybox /sbin/switch_root /sbin/biosdevname /sbin/dmidecode /sbin/cryptsetup"
   if [ "$EC_CRYPT" == "yes" ]; then
      BINARIES="$BINARIES /sbin/cryptsetup"
   fi

   # make a kdump?
   if [ "$DUMP_DEV" ]; then
      if [ "$DUMP_FS" ]; then
         FST=$(getdevtype $DUMP_DEV)
         [ "$FST" == "device-mapper" ] && NEED_MAPPER=yes
         BINARIES="$BINARIES /usr/bin/cp /usr/sbin/makedumpfile"
         KDUMP_CAPTURE=yes
      else
         error "Both dump-dev and dump-fs need to be specified"
         exit 1
      fi
   fi

   # calc all libraries that are needed by binaries
   LIBRARIES=$(for bin in $BINARIES; do ldd $bin | awk '{ print $3 }' | grep /lib; done | sort | uniq)
   # sneaky hidden libraries needed
   LIBRARIES="$LIBRARIES /lib64/libgcc_s.so.1 /lib64/ld-linux-x86-64.so.2"
   
   # same for LVM
   LVM_BIN="/sbin/lvm"
   LVM_LIB=$(ldd /sbin/lvm | awk '{ print $3 }' | grep lib)

   # same for mdadm
   MDADM_BIN="/usr/sbin/mdadm"
   MDADM_LIB=$(ldd $MDADM_BIN | awk '{ print $3 }' | grep lib)

   # If initrd not specified then deduce one based on the version number.
   if [ -z "$INITRD_FIL" ] ; then
      INITRD_FIL=/boot/initrd-$VERSION.img
   fi

   # If kernel library dir not specified, then deduce it
   if [ -z "$KLIBDIR" ] ; then
      KLIBDIR=/lib/modules/$VERSION
   fi
   # The kernel library directory must exist
   if [ ! -d $KLIBDIR ] ; then
      error "$KLIBDIR: no such directory"
      exit 1;
   fi
   
   # Remove the initrd proto directory on exit
   # unless the initrd proto direcrory was given on the command line
   if [ -z "$INITRD_DIR" ] ; then
      INITRD_DIR=$(mktemp -d ${TMPDIR}/initrd.XXXXXXXX)
      trap cleanup EXIT
   fi

   # if not specified, deduce root device from fstab
   if [ -z "$ROOT_DEV" ] ; then
      requirefile $FSTAB
      ROOT_DEV=$(awk '{ if ($1 !~ /^[ \t]*#/ && $2 == "/") { print $1; }}' $FSTAB)
      # root by uuid?
      if [[ $ROOT_DEV =~ ^UUID= ]]; then
         eval $ROOT_DEV
         ROOT_DEV=$(locate_uuid $UUID)
         ROOT_UUID=$UUID
      fi
      # root by label?
      if [[ $ROOT_DEV =~ ^LABEL= ]]; then
         eval $ROOT_DEV
         ROOT_DEV=$(locate_label $LABEL)
         ROOT_LABEL=$LABEL
      fi
   fi

   # validate root dev
   if [ -z "$ROOT_DEV" ] || [ ! -e "$ROOT_DEV" ] ; then
      error "Could not find the root device in /etc/fstab" 1>&2
      exit 1
   fi

   # deduce root device type.
   local ROOT_TYP=$(getdevtype $ROOT_DEV)
   local NEED_STORAGE_MODULES=
   case "$ROOT_TYP" in
   device-mapper)
      NEED_MAPPER=yes
      ;;
   virtblk)
      NEED_STORAGE_MODULES="virtio_blk virtio_pci"
      ;;
   # HYPERV)
   # FIXME: improve detection!
   ide*)
      NEED_STORAGE_MODULES="hv_storvsc hv_utils"
      ;;
   # VMWARE
   # FIXME: improve detection! Scan lspci, maybe?
   sd)
      NEED_STORAGE_MODULES="vmw_pvscsi"
      ;;
   esac

   #Adding nvme, nvme related modules into initrd by default
   NEED_STORAGE_MODULES+=" nvme nvme-core usb-storage "

   for drv in $NEED_STORAGE_MODULES; do
      # cannot use "add" here because "fresh_initrd" will clear INITRD_DIR
      COMMANDS="$COMMANDS +$drv"
      # add module dependencies
      for m in $(modinfo -k "$VERSION" -F depends $drv | tr "," " "); do
         COMMANDS="$COMMANDS +$m"
      done
   done

} # deduce_args

#--------------------------------------------------------------------------------
# check for required file
#--------------------------------------------------------------------------------
requirefile() {
   if [ ! -f "$1" ] ; then
      error "$1: file not found"
      exit 1
   fi
}

#--------------------------------------------------------------------------------
# remove temp working directory
#--------------------------------------------------------------------------------
cleanup() {
   rm -rf $INITRD_DIR
}

#--------------------------------------------------------------------------------
# return true  (0) if ESRT2 RAID pci device found. 
# return false (1) if not found.
# looking for megasr = ESRT2 RAID = pci 0x8086:0xa186:0x8086:0x35cd
#--------------------------------------------------------------------------------

megasr_test() {

   TMP=/tmp/megasr_test.tmp

   # get a list of all pci devices
   for i in /sys/devices/pci* ; do 
      find $i -name subsystem_vendor
   done > $TMP

   # look at each device for an ESRT2 device match
   while read j ; do
      k=$(dirname $j)
      #echo "$(cat $k/vendor)":"$(cat $k/device)":"$(cat $k/subsystem_vendor)":"$(cat $k/subsystem_device)"
      if [ -e $k/vendor ]           && [ "0x8086" == "$(cat $k/vendor)" ]           && \
         [ -e $k/device ]           && [ "0xa186" == "$(cat $k/device)" ]           && \
         [ -e $k/subsystem_vendor ] && [ "0x8086" == "$(cat $k/subsystem_vendor)" ] && \
         [ -e $k/subsystem_device ] && [ "0x35cd" == "$(cat $k/subsystem_device)" ] 
      then
         rm -rf $TMP
         # found a match!
         return 0
      fi
   done < $TMP

   rm -rf $TMP
   # did not find a match
   return 1

} # megasr_test

#--------------------------------------------------------------------------------
# Create a fresh new initrd proto directory
#--------------------------------------------------------------------------------
fresh_initrd() {

   # clone proto type initrd dir
   rm -rf $INITRD_DIR
   mkdir $INITRD_DIR
   mkdir -p $INITRD_DIR/bin $INITRD_DIR/lib64
   cp -r $PROTO/. $INITRD_DIR/.

   rm -f $INITRD_DIR/save-core
   if [ "$EC_CRYPT" == "no" ]; then
      rm -f $INITRD_DIR/bin/exinit
   fi

   # copy binaries
   for bin in $BINARIES ; do
      cp $bin $INITRD_DIR/bin/
   done
   for lib in $LIBRARIES ; do
      cp $lib $INITRD_DIR/lib64/
   done
   ln -s /bin/busybox $INITRD_DIR/bin/sh

   # copy lvm binary
   if [ "$NEED_MAPPER" == "yes" ] ; then
      cp $LVM_BIN $INITRD_DIR/bin/
      # copy lvm libs
      for lib in $LVM_LIB
      do
         cp $lib $INITRD_DIR/lib64/
      done
      # copy lvm conf
      if [ -f /etc/lvm/lvm.conf ] ; then
         mkdir -p $INITRD_DIR/etc/lvm/
         sed 's/verify_udev_operations = 0/verify_udev_operations = 1/' < /etc/lvm/lvm.conf > $INITRD_DIR/etc/lvm/lvm.conf
      fi
   fi
   # copy mdadm binary
        cp $MDADM_BIN $INITRD_DIR/bin  || true
        # copy mdadm libs
        for lib in $MDADM_LIB; do
                cp $lib $INITRD_DIR/lib64 || true
        done
    # copy mdadm.conf
    if [ -f /etc/mdadm.conf ]; then
        cp /etc/mdadm.conf $INITRD_DIR/etc/mdadm.conf  || true
    fi
    mkdir -p $INITRD_DIR/etc/udev
    cp /etc/udev/udev.conf $INITRD_DIR/etc/udev/ || true
    mkdir -p $INITRD_DIR/usr/lib/udev/rules.d/
    UDEV_RULES="
01-md-raid-creating.rules
10-dm.rules
11-dm-lvm.rules
13-dm-disk.rules
50-udev-default.rules
60-persistent-storage.rules
63-md-raid-arrays.rules
65-md-incremental.rules
95-dm-notify.rules
"
    for rule in $UDEV_RULES; do
      if [ -f /usr/lib/udev/rules.d/$rule ] ; then
         cp /usr/lib/udev/rules.d/$rule $INITRD_DIR/usr/lib/udev/rules.d/ || true
      fi
    done
    mkdir -p $INITRD_DIR/usr/lib/systemd/
    cp /usr/lib/systemd/systemd-udevd  $INITRD_DIR/usr/lib/systemd/ || true
    cp /usr/sbin/udevadm $INITRD_DIR/bin/ || true
    UDEVD_LIB=$(ldd /usr/lib/systemd/systemd-udevd | awk '{ print $3 }' | grep lib)
    for lib in $UDEVD_LIB; do
        cp $lib $INITRD_DIR/lib64 || true
    done


   # FIPS Enable
    if [ -x /usr/bin/fipshmac ] ; then
        /usr/bin/fipshmac $INITRD_DIR/lib64/*
    else
        echo "Warning: Initrd is not FIPS signed, install fipscheck rpm"
        sleep 1
    fi

} # fresh_initrd

#--------------------------------------------------------------------------------
# extract an existing initrd
#--------------------------------------------------------------------------------
extract_initrd() {
   rm -rf $INITRD_DIR
   mkdir $INITRD_DIR
   gunzip < $1 | (cd $INITRD_DIR ; cpio -i)
}

#--------------------------------------------------------------------------------
# delete a file; but do not delete if its an essential file
#--------------------------------------------------------------------------------
del() {
   case $1 in
   init | bin/busybox)
      error "$1: will not remove"
      ;;
   rc.local)
      rm -f $INITRD_DIR/etc/rc.local
      ;;
   */*)
      rm -r $INITRD_DIR/$1
      ;;
   *)
      if [ -f $INITRD_DIR/lib/modules/$VERSION/$1 ] ; then
         rm $INITRD_DIR/lib/modules/$VERSION/$1
      elif [ -f $INITRD_DIR/lib/modules/$VERSION/$1.ko ]; then
         rm $INITRD_DIR/lib/modules/$VERSION/$1.ko
      else
         error "$1: module not found"
      fi
      ;;
   esac
} # del

#--------------------------------------------------------------------------------
# give a name, find the full path to kernel module
#--------------------------------------------------------------------------------
findmod() {
   case $(find $KLIBDIR -name $1 | wc -l) in
   0)
# Replacing underscores with hypen ; hypen with underscore , when module not found at 1st attempt
     if [ -z $flag ] ; then
          aa=${1/_/@}
          bb=${aa/-/_}
          aa=${bb/@/-}
          flag=1
          findmod $aa
     else
        unset flag
        echo $1: module not found
     fi
     ;;
   1)
      find $KLIBDIR -name $1
      ;;
   *)
      error "Multiple modules found:"
      find $KLIBDIR -name $1 1>&2
      ;;
   esac
} # findmod

#--------------------------------------------------------------------------------
# copy module to initrd, and all its module dependencies
#--------------------------------------------------------------------------------
copymod() {

   M="$1" # module name, e.g. "ahci.ko"

   # create modules dir if needed
   [ -d $INITRD_DIR/lib/modules/$VERSION ] || mkdir -p $INITRD_DIR/lib/modules/$VERSION

   L=$(grep "/$M:" /lib/modules/$VERSION/modules.dep)
   for M in $L ; do
      # remove colon from first arg
      M="${M/:/}"
      # copy each depend
      cp /lib/modules/$VERSION/$M $INITRD_DIR/lib/modules/$VERSION/
   done

} # copymod

#--------------------------------------------------------------------------------
# add a file to the initrd image
#--------------------------------------------------------------------------------
add() {
   local MOD

   # find needed module
   MOD=
   case $1 in
      init | bin/busybox)
         error "$1: will not replace"
         ;;
      rc.local)
         cp rc.local $INITRD_DIR/etc/rc.local
         ;;
      *.ko)
         MOD=$(findmod $(basename "$1"))
         ;;
      */*)
         if [ -d $INITRD_DIR/$1 ] ; then
            error "$1: is a directory"
         else
            mkdir -p $INITRD_DIR/$(dirname $1)
            cp $1 $INITRD_DIR/$1
         fi
         ;;
      *)
         MOD=$(findmod $1.ko)
         ;;
   esac

   # did we find a module?
   if [ -n "$MOD" ] ; then
      MODNAME=$(basename "$MOD")

      # don't add same module twice
      if [[ "$MODULE_LIST" =~ " $MODNAME " ]] ; then
         : # its already in list
      else
         # add module to initrd load list
         if [ -z "$MODULE_LIST" ] ; then
            MODULE_LIST=" $MODNAME "
         else
            MODULE_LIST="$MODULE_LIST $MODNAME "
         fi

         # create modules dir if needed
         [ -d $INITRD_DIR/lib/modules/$VERSION ] || mkdir -p $INITRD_DIR/lib/modules/$VERSION
   
         # copy module to initrd, and all its module dependencies
         # copymod "$MODNAME"
         # no need for copymod because /sbin/findmodules gives all depends 
         cp $MOD $INITRD_DIR/lib/modules/$VERSION/
      fi
   fi

} # add

# add several from one line
adds() {
   for i in $* ; do
      add $i
   done
} 

#--------------------------------------------------------------------------------
# provide "--list" option to list all the non-standard files in initrd img
#--------------------------------------------------------------------------------
list_cmd() {

if [ "$LIST_CMD" == "yes" ] ; then

   # validate given initrd file exists
   if [ -z "$INITRD_FIL" ] ; then
      error "The --list cmd requies image specified with --initrd"
      exit 0
   elif [ ! -e "$INITRD_FIL" ] ; then
      error "Image specified with --initrd does not exist"
      exit 0
   fi

   # get the long listing from cpio
   # use AWK to trim any leading ./ off of the file names
   # and only print the names of regular files
   gunzip < $INITRD_FIL | cpio --quiet -tv |
   awk '{ sub("\\./", "", $NF); if (substr($1, 1, 1) == "-") print $NF; }' |
   while read file ; do
      case $file in
      bin/busybox | bin/lvm | bin/kpartx | bin/dmraid | bin/dmsetup | init | */modules.*)
         ;;
      etc/rc.local)
         log rc.local
         ;;
      *.ko)
         log $(basename "$file")
         ;;
      *)
         log $file
      esac
   done
   exit 0
fi

} # list_cmd

#--------------------------------------------------------------------------------
# Now add/delete any modules/files specified, if any
#--------------------------------------------------------------------------------
add_files() {
   for cmd in $COMMANDS ; do
   case $cmd in
   -*)
      del ${cmd#-}
      ;;
   +*)
      add ${cmd#+}
      ;;
   *)
      error "Internal error: received command $cmd"
      exit 1
      ;;
   esac
   done
} # add_files

#--------------------------------------------------------------------------------
# sata and megasr drivers are no longer built-in.
# megasr must come before ahci for ESRT2 mobo raid to be detected
#--------------------------------------------------------------------------------
add_hdd() {
   rc=1

   # get module used for /boot e.g. "sda1"
   if grep -q " /boot " /proc/mounts ; then
      tmp=$(grep " /boot " /proc/mounts | tail -1 | cut -d' ' -f1 | xargs basename | xargs /sbin/findmodules) 2>/dev/null
      rc=$?
   fi

   # if none, try root / e.g. "sda3"
   if [ $rc -ne 0 ] || [ -z "$tmp" ] ; then
      tmp=$(grep " / " /proc/mounts | tail -1 | cut -d' ' -f1 | xargs basename | xargs /sbin/findmodules) 2>/dev/null
      rc=$?
   fi

   # if none, try lvm-partition - fs-root 
   if [ $rc -ne 0 ] || [ -z "$tmp" ] ; then
      tmp=$(grep " / " /proc/mounts | cut -d' ' -f1 ) 2>/dev/null
      if [ "x$tmp" = 'x/dev/fs/root' ] ; then
          tmp=$(pvdisplay -c | tail -1 | cut -d":" -f1 | xargs basename | xargs findmodules) 2>/dev/null
          rc=$?
      fi
   fi

   # none found? not good.
   if [ $rc -ne 0 ] || [ -z "$tmp" ] ; then
      error "mkinitrd:add_hdd: Warning: No module found for disk. It maybe builtin to the kernel."

   # found but builtin
   elif grep -q "$tmp" /lib/modules/$VERSION/modules.builtin ; then
      : # log "mkinitrd:add_hdd: hard disk driver $tmp is kernel builtin."

   # found module
   else
      for i in $tmp ; do add $i; done
   fi

} # add_hdd

#--------------------------------------------------------------------------------
# if using LVM, then add any currently loaded "dm" modules
#--------------------------------------------------------------------------------
add_lvm() {

   if [ "$NEED_MAPPER" == "yes" ] ; then
      # LVM module
      add dm-mod
   fi

} # add_lvm
add_md() {
        add md-mod
        add raid1
} # add_md


#--------------------------------------------------------------------------------
# add encryption modules
#--------------------------------------------------------------------------------
add_usbcrypt() {
   # Add USB Modules, required for encryption password , mounting usbdisk
   adds dm-crypt ehci_hcd ehci_pci usb_storage dm_crypt dm_mod efivars ir_usb irqbypass ums_usbat xhci_hcd xhci_pci ums-usbat ir-usb usbserial ezusb
}

#--------------------------------------------------------------------------------
# if using virtualization, then add any currently loaded virtualization modules
#--------------------------------------------------------------------------------
add_virt() {

    for M in $(awk {'print $1'} /proc/modules) ; do
        case $M in
            vmx*|vmw*|vmh*|virtio*|hv_*|hyperv_fb*) add $M ;;
         # these modules have filenames with dash, but module names with underscore.
            xen*|kvm*|*hyperv*) add ${M/_/-} ;;
        esac
    done

} # add_virt

#--------------------------------------------------------------------------------
# if there are any modules in initrd, then create modules.dep
#--------------------------------------------------------------------------------
add_dep() {
   if [ -n "$MODULE_LIST" ] ; then
      depmod -v -b $INITRD_DIR $VERSION 1>/tmp/depmod.txt 2>&1
     sleep 1
   fi
} # add_dep

#--------------------------------------------------------------------------------
# Add intel microcode to initrd, but skip microcode if this is virtualizaiton.
# This uses the required & strange method detailed in kernel docs:
# linux-4.9/Documentation/x86/early-microcode.txt
#--------------------------------------------------------------------------------
add_ucode() {
   ucode_file=""
   BOOT_DIR=$(dirname $INITRD_FIL)

   # do not add ucode if we are running under virtualization
   # FYI: vmid return code 0 = real-hardware, >0 = virtualization
   if ! vmid ; then 
      echo "Do not add microcode to initrd on virtualized platforms."
      return
   fi

   # get name of firmware file for this CPU, if any
   if [ "$KDUMP_CAPTURE" != "yes" ] && \
      [ -x /usr/bin/intel-ucode-chk ] ; then
         ucode_file=$(/usr/bin/intel-ucode-chk | awk '{ print $NF }')
   fi

   # if firmware found, and not kdump, then add microcode to initrd
   if [ -e "$ucode_file" ] ; then
      # make a cpio of just the ucode file
      D=$(mktemp -d)
      mkdir -p $D/work/kernel/x86/microcode
      cp $ucode_file $D/work/kernel/x86/microcode/GenuineIntel.bin
      cd $D/work
      find . | cpio -o -H newc >$BOOT_DIR/ucode.cpio 2>/dev/null
      # save orig initrd img
      cd $BOOT_DIR
      INITRD_OLD=${INITRD_FIL/.img/.pre}
      mv $INITRD_FIL $INITRD_OLD
      # record size of ucode.cpio
      echo $ucode_file >$INITRD_FIL.ucode 
      ucode_size=$(stat -c '%s' ucode.cpio)
      echo "ucode.cpio size (bytes): $ucode_size" >>$INITRD_FIL.ucode 
      # combine ucode cpio & initrd img to make new combined initrd
      cat ucode.cpio $INITRD_OLD >$INITRD_FIL
      log "mkinitrd: Intel microcode $ucode_file added to $INITRD_FIL"
      rm -rf $D ucode.cpio
      # if empty file "/boot/debug" exist, then leave pre-ucode initrd
      [ -e /boot/debug ] || rm $INITRD_OLD
   fi
} # add_ucode

#--------------------------------------------------------------------------------
# Pass the modules and root information for the running initrd to use.
# Although the running initrd could determine the modules present the list
# we pass through will preserve order (to help load dependencies).
#--------------------------------------------------------------------------------
boot_cnf() {
   (
   echo modules=\"$MODULE_LIST\"
   if [ "$KDUMP_CAPTURE" == "yes" ]; then
      echo dump_dev=\"$DUMP_DEV\"
      echo dump_fs=\"$DUMP_FS\"
   else
      if [ -n "$ROOT_UUID" ]; then
         echo root=\"UUID=$ROOT_UUID\"
      elif [ -n "$ROOT_LABEL" ]; then
         echo root=\"LABEL=$ROOT_LABEL\"
      else
         echo root=\"$ROOT_DEV\"
      fi
      if [ "$EC_CRYPT" == "yes" ]; then
         echo ec_root=\"$CRYPT_DEV\"
         echo boot_dev=\"$BOOT_DEV\"
      fi
   fi
   ) > $INITRD_DIR/boot.cnf
} # boot_cnf

#--------------------------------------------------------------------------------
# create a initrd.img from the proto directory
#--------------------------------------------------------------------------------
mk_initrd() {
   log "Creating $INITRD_FIL ..."
   (cd $INITRD_DIR && find . | cpio --quiet -H newc -o ) | gzip > $INITRD_FIL
}

#--------------------------------------------------------------------------------
# make a kdump initrd
#--------------------------------------------------------------------------------
kdump_initrd() {
 if [ "$KDUMP_CAPTURE" == "yes" ]; then
   # need to change the name of cp as init will overwrite it
   cp /usr/bin/cp $INITRD_DIR/bin/xcp
   cp /usr/lib/initrd/save-core $INITRD_DIR/etc/rc.local
   if [ ! -x /usr/sbin/makedumpfile ]; then
      echo "missing makedumpfile, install rpm kexec-tools" >&2
      exit 1
   fi
   if [ ! -r /usr/lib/debug/lib/modules/$VERSION/vmlinux ]; then
      echo "missing vmlinux, install rpm kernel-debuginfo" >&2
      exit 1
   fi
   echo creating vmcoreinfo ...
   makedumpfile -g $INITRD_DIR/etc/vmcoreinfo -x /usr/lib/debug/lib/modules/$VERSION/vmlinux
 fi
}

#--------------------------------------------------------------------------------
# MAIN
#--------------------------------------------------------------------------------
parse_args $*   # parse command line arguments
deduce_args     # calculate any missing args
list_cmd        # perform list cmd if requested
fresh_initrd    # create a fresh initrd working dir
add_files       # add/del any specified modules/files to initrd
add_hdd         # add megasr and ahci, no longer built-in
add_lvm         # if using LVM, then add "dm" modules
add_md
add_usbcrypt    # add dm-crypt , USB modules
kdump_initrd    # create kdump if requested
add_virt        # if using virtualization, then add vm modules
adds libata libahci ahci # add sata modules for hard drives
add megaraid_sas # Megaraid
add autofs4     # add autofs4 needed by automounter
add xfs         # add xfs module for mounting of XFS fs
add_dep         # if any modules added, then copy modules.dep
boot_cnf        # create boot.cnf of kernel modules and root dev
mk_initrd       # Finally, package initrd dir into an img file
add_ucode       # add microcode _after_ build of initrd img

### TO-DO
# 1. if called from running system, instead of the installer, 
#       then also add any currently loaded modules to the new initrd.
#       make the list from /proc/modules, then add all in one modprobe,
#       so that it may deduce correct order to load
# 2. if called from installer, try to figure out any NIC modules,
#       from /proc/modules LIVE and add those to initrd.
# 3. from init.sh specify all mods at once to modprobe 
#       so it may determine the correct order.

