#!/bin/sh
set -e
# amd64-microcode initramfs-tools hook script
# Copyright (C) 2012-2016 Henrique de Moraes Holschuh <hmh@debian.org>
# Copyright (C) 2019 Canonical Ltd
# Released under the GPL v2 or later license
#
# Generates a copy of the minimal microcode for all AMD processors
# and installs it to the early initramfs

EFWE=$(realpath "$1")
EFWD=$(mktemp -d "${TMPDIR:-/var/tmp}/mkinitramfs-EFW_XXXXXXXXXX")
EFWCD="${EFWD}/d/kernel/x86/microcode"
# note: to build a reproducible early initramfs, we force
# the microcode component ordering inside the microcode
# firmware file, as well as the timestamp and ordering of
# all cpio members.
mkdir -p "${EFWCD}"
find /lib/firmware/amd-ucode/ -maxdepth 1 -type f -print0 | LC_ALL=C sort -z | xargs -0 -r cat 2>/dev/null >"${EFWCD}/AuthenticAMD.bin"
iucode_tool --write-to="${EFWCD}/GenuineIntel.bin" /lib/firmware/intel-ucode/
find "${EFWD}" -print0 | xargs -0r touch --no-dereference --date="@0"
( cd "${EFWD}/d" ; find . -print0 | LC_ALL=C sort -z | cpio --null --reproducible -R 0:0 -H newc -o --quiet > "${EFWE}" )
[ -d "${EFWD}" ] && rm -fr "${EFWD}"
