#/bin/bash

#%stage: boot
#
#  Adds AMD microcode to the initrd
#
#  If processor(s) are upgraded on the system, mkinitrd has to be re-called
#  manually to include a possible other needed firmware to the initrd
#

if grep -q -i AuthenticAMD /proc/cpuinfo; then
        echo -n "Microcode: "
        if [ ! -e /lib/firmware/amd-ucode ];then
            echo "AMD microcode not found, amd-ucode package not installed?"
            return 0
        fi
        fam=`head /proc/cpuinfo |sed -n -e 's/cpu family.*: \([0-9]\+\)/\1/p'`
        # Only try to update when family >= 16 (0x10, fam 10h)
        if [ $fam -ge 16 >& /dev/null ];then
            # Family 0x15 firmware is named: microcode_amd_famXXh.bin"
	    if [ $fam -lt 21 >& /dev/null ];then
                file=microcode_amd.bin
            else
                file=`printf "microcode_amd_fam%xh.bin" $fam`
            fi
            if [ -e /lib/firmware/amd-ucode ];then
                echo "Adding AMD microcode $file"
                mkdir -p $tmp_mnt/lib/firmware/amd-ucode
                cp /lib/firmware/amd-ucode/"$file"* $tmp_mnt/lib/firmware/amd-ucode
            else
                echo "No AMD microcode found, amd-ucode package not installed?"
	    fi
        else
            printf "AMD CPU family: 0x%x does not support microcode updates" $fam
        fi
fi