#!/bin/bash
set -x

export LANG=C

TMPDIR=$(mktemp -d)
trap "rm -rf '${TMPDIR}'" EXIT

#KEYSERVER='hkp://pool.sks-keyservers.net'
KEYSERVER='hkp://pgp.mit.edu'
GPG="gpg --quiet --batch --no-tty --no-permission-warning --keyserver "${KEYSERVER}" --homedir ${TMPDIR}"

pushd "$(dirname "$0")" >/dev/null

$GPG --gen-key <<EOF
%echo Generating Parabola Keyring keychain master key...
Key-Type: RSA
Key-Length: 1024
Key-Usage: sign
Name-Real: Parabola Keyring Keychain Master Key
Name-Email: parabola-keyring@localhost
Expire-Date: 0
%no-protection
%commit
%echo Done
EOF

rm -rf packager parabola-trusted
mkdir packager

while read -ra data; do
	keyid="${data[0]}"
	username="${data[@]:1}"
	${GPG} --recv-keys ${keyid} &>/dev/null
	printf 'lsign\ny\ny\nsave\ny\n' | \
		${GPG} --command-fd 0 --edit-key ${keyid}
	echo "${keyid}:4:" | tee -a parabola-trusted
done < packager-keyids
${GPG} --import-ownertrust < parabola-trusted 2>/dev/null

while read -ra data; do
	keyid="${data[0]}"
	username="${data[@]:1}"
	printf 'clean\nquit\n' | \
		${GPG} --command-fd 0 --edit-key ${keyid}
	FD=$(mktemp)
	exec 4>"${FD}"
	if ! ${GPG} --list-keys --with-colons ${keyid} 2>/dev/null | grep -q '^pub:f:'; then
		echo "key is not fully trusted: ${keyid} ${username}"
	else
		${GPG} --armor --output packager/${username}.asc --export ${keyid}
	fi
done < packager-keyids

cat packager/*.asc > parabola.gpg

popd >/dev/null

if which neato &>/dev/null ; then
  ${GPG} --list-sigs | perl ./sig2dot.pl | tee parabola-keyring.dot | neato -Tpng -o parabola-keyring-$(date +%Y.%m.%d).png && \
  echo "WoT graphed as parabola-keyring-$(date +%Y-%m%-d).png"
else
  echo "Install graphviz to generate a graph of parabola-keyring's web of trust."
fi

echo $TMPDIR
rm -rf /tmp/tmp.*
