#!/bin/bash

set -e

su - debian-sks -c 'mkdir -p /var/lib/sks/dump'

# avoid the network-based import, just use the debian keyring
for x in  /usr/share/keyrings/debian-*.gpg; do
    cp "$x" "/var/lib/sks/dump/$(basename "$x" .gpg).pgp"
done

su - debian-sks -c /usr/share/sks/sks-db-setup 2> "${AUTOPKGTEST_ARTIFACTS}/sks-db-setup.stderr"

systemctl enable sks
systemctl start sks

export GNUPGHOME="$AUTOPKGTEST_TMP/gpg"
rm -rf "$GNUPGHOME"
mkdir -p -m 0700 "$GNUPGHOME"
echo keyserver hkp://127.0.0.1 > "${GNUPGHOME}/dirmngr.conf"
cat > "${GNUPGHOME}/gpg.conf" <<EOF
with-colons
batch
fixed-list-mode
quiet
EOF

# should not have the release key already:
if gpg --with-colons --list-keys ='Debian Stable Release Key (9/stretch) <debian-release@lists.debian.org>' 2>/dev/null; then
    printf 'We have the release key already!\n' >&2
    exit 1
fi

# test looking for keys on the keyserver
gpg --search 'Debian Stable Release Key (9/stretch) <debian-release@lists.debian.org>' >"${AUTOPKGTEST_ARTIFACTS}/stable-release-keyserver.output" 2>/dev/null

diff -u "${AUTOPKGTEST_ARTIFACTS}/stable-release-keyserver.output" debian/tests/stable-release-keyserver.expected

# test actually receiving keys from the keyserver

gpg --recv 067E3C456BAE240ACEE88F6FEF0F382A1A7B6500

gpg --with-colons --list-keys ='Debian Stable Release Key (9/stretch) <debian-release@lists.debian.org>' > "${AUTOPKGTEST_ARTIFACTS}/postimport-list.output"

diff -u <(grep -v ^tru < "${AUTOPKGTEST_ARTIFACTS}/postimport-list.output") debian/tests/postimport-list.expected

# TODO: test sending keys to the keyserver, and trying to recover them

# TODO: set up a second keyserver, configure recon between them

# TODO: test sending a key to one keyserver, ensuring that a new key is synchronized
