#!/bin/bash
# intel-ucode-ird.sh
# make new initrd to contain ucode

# do nothing if ucode not found for this CPU model
ucode_file=$(/usr/bin/intel-ucode-chk | awk '{ print $NF }')
if [ ! -e "$ucode_file" ] ; then
   ## intel-ucode-chk prints a status msg; no message needed here
   exit 0
fi

# do not add ucode to initrd 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."
   exit 0
fi

# get current initrd, e.g. "/boot/initrd-4.9.100-1.mlos3.x86_64.img"
#I=$(/bin/ls -1tr /boot/initrd-*img | tail -1)
# get current kernel ver-rel, e.g. "4.9.100-1.mlos3.x86_64"
#V=$(echo $I | sed -e 's/.*initrd-//' -e 's/.img//')

# current running kernel initrd ver, e.g. "4.9.100-1.mlos3.x86_64"
V=$(uname -a | awk '{print $3}')
# current initrd filename should be this
I="/boot/initrd-$V.img"

# if this initrd not found, then take latest from /boot
if [ ! -e $I ] ; then
   I=$(ls -1 /boot/initrd* 2>/dev/null | sort | tail -1) 
   V=$(echo $I | sed -e 's/.*initrd-//' -e 's/.img//')
fi

# sanity check initrd name
if [ ${#I} -gt 9  -a  -e $I ] ; then
   echo "Updating $I ver $V with latest installed intel-ucode."
else
   # echo "Note: No initrd found."
   exit 0
fi

# make new initrd with latest ucode
/sbin/mkinitrd --fresh --force --version $V --output $I
rc=$?
if [ $rc != 0 ] ; then
   echo "Error $rc running cmd: /sbin/mkinitrd --fresh --force --version $V --output $I"
   exit 2
fi

exit 0

