#!/bin/sh
unsigned_version="$1"
version="$2"
abi="$3"

mkdir -p SIGNED
signed="$(pwd)/SIGNED"
cd "$version/boot" || exit 1
for s in *.efi.signed; do
	[ ! -f "$s" ] && continue
	base=$(echo "$s" | sed -e 's/.efi.signed//')
	flavour=$(echo "$base" | sed -e "s@.*-$abi-@@")
	verflav="$abi-$flavour"
	if [ -e /usr/lib/linux/$verflav/canonical-revoked-certs.pem ]; then
		awk 'BEGIN {c=0;} /Certificate:/{c++} { print > "revoked-cert." c ".pem"}' < /usr/lib/linux/$verflav/canonical-revoked-certs.pem
		for cert in revoked-cert.*.pem; do
			echo "Checking signature against $cert"
			if sbverify --verbose --verbose --cert $cert $s; then
				echo "Which is bad. EFI binary signed with revoked cert $cert"
				exit 1
			fi
		done
		echo "All good. EFI binary not signed with a revoked key."
	fi
	(
		vars="${base}.efi.vars"
		[ -f "$vars" ] && . "./$vars"
		if [ "$GZIP" = "1" ]; then
			gzip -9 -n "$s"
			mv "${s}.gz" "$s"
		fi
	)
	chmod 600 "$s"
	ln "$s" "$signed/$base"
done
for s in *.opal.sig; do
	[ ! -f "$s" ] && continue
	base=$(echo "$s" | sed -e 's/.opal.sig//')
	cat "$base.opal" "$s" >"$signed/$base"
	chmod 600 "$signed/$base"
done
for s in *.sipl.sig; do
	[ ! -f "$s" ] && continue
	base=$(echo "$s" | sed -e 's/.sipl.sig//')
	cat "$base.sipl" "$s" >"$signed/$base"
	chmod 600 "$signed/$base"
done
for s in *.fit.signed; do
	[ ! -f "$s" ] && continue
	chmod 600 "$s"
	base=$(echo "$s" | sed -e 's/.fit.signed//')
	ln "$s" "$signed/$base"
done
for s in *.noop; do
	[ ! -f "$s" ] && continue
	chmod 600 "$s"
	base=$(echo "$s" | sed -e 's/.noop//')
	ln "$s" "$signed/$base"
done
