#!/bin/bash
# Self-contained reproduction of two recipient-selection bugs in GnuPG 2.4.7
# (still present in a pristine 2.4.7). Forges minimal throwaway certificates in
# a temporary keyring and tries to encrypt to addresses that are plainly
# present and usable. No network, no external key.
#
# Copyright © 2026 Jean-Jacques Brucker (u4=sRyUhEbNU5OwyLEjfSwaXAe_42.17-002.76) <jjbrucker@foopgp.org>
# Copyright © 2026 Mnêmê (u5001777236237.945e_43.30_005.38 claude-opus-5) <mneme@foopgp.org>
#
# Usage: ./repro.sh

set -e

export GNUPGHOME="$(mktemp -d)"; trap 'rm -rf "$GNUPGHOME"' EXIT

echo
echo "Self-contained reproduction of two recipient-selection bugs in gpg"
echo "Tested version: $(gpg --version | head -n1)"

gpgbatch="gpg --batch --yes --pinentry-mode loopback --passphrase "" --quiet --no-auto-check-trustdb"

photo="$GNUPGHOME/p.jpg"
printf '\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xd9' > "$photo"

get_fpr(){ gpg --with-colons --list-keys "$1" | awk -F: '$1=="fpr"{print $10;exit}'; }

try_encrypt(){ if echo x | gpg --batch --yes --trust-model always --encrypt -r "$1" -o /dev/null
       then echo ENCRYPTS; else echo "REFUSED ($?)"; fi; }

echo -e "\n---\n"

echo "Bug 1 — https://github.com/foopgp/gnupg/commit/a445a5079a85c5190cd69021c673c4aac0658732"
echo "try encrypt to alice@example.org, which is on a revoked user id AND a usable twin:"

set -x
$gpgbatch --quick-gen-key 'Alice <alice@example.org>' default default never
fpr=$(get_fpr alice@example.org)
$gpgbatch --quick-add-uid "$fpr" 'Alice Example <alice@example.org>'
$gpgbatch --quick-revoke-uid "$fpr" 'Alice <alice@example.org>'
try_encrypt alice@example.org
set +x

echo -e "\n---\n"

echo "Bug 2 — https://github.com/foopgp/gnupg/commit/06fc94b552ed8fb9e92ee64e3871d522863c2f0a"
echo -e "try encrypt to carol@work.example usable uid, placed after a revoked photo id:\n"

set -x
$gpgbatch --quick-gen-key 'Carol <carol@example.org>' default default never
fpr=$(get_fpr carol@example.org)
printf '%s\n' addphoto "$photo" save | gpg --batch --yes --pinentry-mode loopback --passphrase "" --photo-viewer /bin/true --command-fd 0 --edit-key "$fpr"
printf '%s\n' 'uid 2' revuid y 0 '' y save | gpg --batch --yes --pinentry-mode loopback --passphrase "" --command-fd 0 --edit-key "$fpr"
$gpgbatch --quick-add-uid "$fpr" 'Carol Work <carol@work.example>'
try_encrypt carol@work.example
set +x

echo -e "\n---\n"
