#!/bin/sh
# upstream-keys - rebuild debian/upstream/signing-key.asc from kernel.org's
# WKD, or check it: the keys must be exactly the two whose fingerprints
# kernel.org publishes at https://www.kernel.org/signature.html
#
# usage: upstream-keys [--check]

set -e

keys="$(readlink -f "$(dirname "$0")/../upstream/signing-key.asc")"
# Linus Torvalds, Greg Kroah-Hartman
want="647F28654894E3BD457199BE38DBBDC86092693E
ABAF11C65A2970B130ABE3C479BE3E4300411886"

# primary fingerprints in an armoured key file, sorted
fprs() {
	gpg --batch --with-colons --show-keys "$1" |
		awk -F: '/^pub/ { p = 1; next } /^sub/ { p = 0 } /^fpr/ && p { print $10; p = 0 }' | sort
}

if [ "${1:-}" != --check ]; then
	GNUPGHOME="$(mktemp -d)"
	export GNUPGHOME
	trap 'rm -rf "$GNUPGHOME"' EXIT
	gpg --batch -q --auto-key-locate clear,wkd --locate-keys torvalds@kernel.org gregkh@kernel.org > /dev/null
	printf '%s\n' "$want" | xargs gpg --batch --armor --export-options export-minimal --export > "$keys"
fi

have="$(fprs "$keys")"
if [ "$have" != "$want" ]; then
	printf 'upstream-keys: %s has\n%s\nwanted\n%s\n' "$keys" "$have" "$want" >&2
	exit 1
fi
gpg --batch --show-keys "$keys" | grep -E '^pub|^uid'
echo "upstream-keys: ok"
