#!/bin/sh
# Adds a new key
set -e

if [ -z "$1" ] || [ -z "$2" ]; then
	echo "Usage: add-key keyfile dir" >&2
	exit 1
fi

# avoid gnupg touching ~/.gnupg
GNUPGHOME=$(mktemp -d -t jetring.XXXXXXXX)
export GNUPGHOME
trap cleanup exit
cleanup () {
	rm -rf "$GNUPGHOME"
}

keyfile=$(readlink -f "$1") # gpg works better with absolute keyring paths
keydir="$2"

basename=$(basename "$keyfile")
date=`date -R`

keyid=$(gpg --keyid long --options /dev/null --no-auto-check-trustdb < $keyfile | grep '^pub' | sed -e 's!.*/!!' -e 's/ .*//')

if [ -e $keydir/0x$keyid ]; then
	echo "0x$keyid already exists in $keydir - existing key or error."
	exit 1
fi

# Check we have our keyrings available for checking the signatures
if [ ! -e output/keyrings/debian-keyring.gpg -o \
		-e output/keyrings/debian-keyring.pgp -o \
		-e output/keyrings/extra-keys.pgp ]; then
	make
fi

gpg --import $keyfile
gpg --keyring output/keyrings/debian-keyring.gpg \
	--keyring output/keyrings/debian-keyring.pgp \
	--keyring output/keyrings/extra-keys.pgp --check-sigs 0x$keyid

echo "Are you sure you want to update this key? (y/n)"
read n

if [ "x$n" = "xy" -o "x$n" = "xY" ]; then
	gpg --no-auto-check-trustdb --options /dev/null \
		--export $keyid > $keydir/0x$keyid
	bzr add $keydir/0x$keyid
else
	echo "Not adding key."
fi
