#!/bin/sh
# amd64-microcode initramfs-tools hook script
# Copyright (C) 2012-2014 Henrique de Moraes Holschuh <hmh@debian.org>
# Released under the GPL v2 or later license
#
# Generates a copy of the minimal microcode for the current system if
# possible, and installs it in the initramfs.
#

PREREQ=""
AMD64UCODE_CONFIG=/etc/default/amd64-microcode

prereqs()
{
   echo "$PREREQ"
}

case $1 in
prereqs)
   prereqs
   exit 0
   ;;
esac

. /usr/share/initramfs-tools/hook-functions

verbose()
{
	if [ "${verbose}" = "y" ] ; then
		echo "amd64-microcode: $*"
	fi
	:
}

AUCODE_FW_DIR=/lib/firmware/amd-ucode
AMD64UCODE_INITRAMFS=auto
[ -r ${AMD64UCODE_CONFIG} ] && . ${AMD64UCODE_CONFIG}

[ -z "${AMD64UCODE_INITRAMFS}" ] && AMD64UCODE_INITRAMFS=no

if [ ! -d "${AUCODE_FW_DIR}" ] ; then
	verbose "no AMD64 processor microcode datafiles to install"
	exit 0;
fi

case "${AMD64UCODE_INITRAMFS}" in
    no|0)
        verbose "disabled by ${AMD64UCODE_CONFIG}"
        exit 0
        ;;
    early)
	echo "W: amd64-microcode: early mode not supported, forcing late initramfs mode" >&2
        AMD64UCODE_INITRAMFS=yes
        ;;
    yes|1|auto)
        ;;
    *)
        echo "E: amd64-microcode: invalid AMD64UCODE_INITRAMFS, using automatic mode" >&2
        AMD64UCODE_INITRAMFS=auto
esac

if [ "${AMD64UCODE_INITRAMFS}" = "auto" ] ; then
        grep -q "^vendor_id[[:blank:]]*:[[:blank:]]*.*AuthenticAMD" /proc/cpuinfo || {
                verbose "no AMD processors detected, nothing to do"
                exit 0
        }
fi

# See Debian bug #716917.  Blacklist all non-LTS/non-Debian kernel versions
# before kernel 3.4  Only known-bad kernel is 2.6.38.
#
# This doesn't blacklist early kernels in the LTS branches, we don't have enough
# information at the initramfs-tools layer, due to the way Debian and Ubuntu version
# kernel packages.

if dpkg --compare-versions "${version}" le 3.4 && \
     { dpkg --compare-versions "${version}" lt 2.6.32 || \
      { dpkg --compare-versions "${version}" ge 2.6.33 && dpkg --compare-versions "${version}" lt 3.0 ; } || \
      { dpkg --compare-versions "${version}" ge 3.1 && dpkg --compare-versions "${version}" lt 3.2 ; } || \
      dpkg --compare-versions "${version}" ge 3.3 ; \
     }; then
	echo "E: amd64-microcode: unsupported kernel version!" >&2
	exit 0
fi

verbose "installing all microcode datafiles for AMD64 processors"

# Generate firmware dir
mkdir -m 755 -p "${DESTDIR}${AUCODE_FW_DIR}" || true
cp -fr "${AUCODE_FW_DIR}/." "${DESTDIR}${AUCODE_FW_DIR}/."

if ! rmdir "${DESTDIR}${AUCODE_FW_DIR}" 2>/dev/null ; then
	# The directory was not empty, so we have work to do
	verbose "installing AMD64 processor microcode update support into initramfs..."
	force_load microcode
fi

:
