#!/usr/bin/env bash
# Verify the official FFmpeg 9.0 detached signature in an isolated GnuPG home.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
EXPECTED_FINGERPRINT=FCF986EA15E6E293A5644F10B4322F04D67658D8
WORK=$(mktemp -d /private/tmp/neocodec-ffmpeg-signature.XXXXXX)
cleanup() { rm -rf "$WORK"; }
trap cleanup EXIT
chmod 700 "$WORK"

for file in ffmpeg-9.0.tar.xz ffmpeg-9.0.tar.xz.asc ffmpeg-devel.asc; do
  [ -f "$SCRIPT_DIR/$file" ] && [ ! -L "$SCRIPT_DIR/$file" ] || {
    echo "ERROR: missing/non-regular signature input: $file" >&2
    exit 1
  }
done

gpg --batch --homedir "$WORK" --import "$SCRIPT_DIR/ffmpeg-devel.asc" >/dev/null 2>&1
fingerprint=$(gpg --batch --homedir "$WORK" --with-colons --fingerprint \
  | awk -F: '$1 == "fpr" { print $10; exit }')
[ "$fingerprint" = "$EXPECTED_FINGERPRINT" ] || {
  echo "ERROR: signing-key fingerprint is '$fingerprint', expected $EXPECTED_FINGERPRINT" >&2
  exit 1
}
status=$(gpg --batch --homedir "$WORK" --status-fd 1 \
  --verify "$SCRIPT_DIR/ffmpeg-9.0.tar.xz.asc" "$SCRIPT_DIR/ffmpeg-9.0.tar.xz" 2>/dev/null)
grep -Fq "[GNUPG:] VALIDSIG $EXPECTED_FINGERPRINT " <<< "$status" || {
  echo "ERROR: FFmpeg 9.0 detached signature is not valid for $EXPECTED_FINGERPRINT" >&2
  exit 1
}
echo "PASS: FFmpeg 9.0 source signature is valid for $EXPECTED_FINGERPRINT"
