#!/bin/sh
# fetch missing keys signed by local keys

set -e

if [ $# -gt 0 ]; then
	mykeys="$1"
	shift
fi

# set e.g. GPG=gpg2 in environment to override binary to use
GPG=${GPG:-gpg}

# my keys are those with a corresponding secret key
mykeys=${mykeys:-$($GPG --batch --no-auto-check-trustdb --list-secret-keys --with-colons | grep '^sec' | cut -d: -f5)}
if [ -z "$mykeys" ]; then
	# exit if no key string
	echo "Can't get user's key ID"
	exit 1
fi

# all of the people without key locally who have signed my key
mysigners=$(LC_ALL=C $GPG --batch --no-auto-check-trustdb --list-sigs --with-colons $mykeys | grep '^sig.*User ID not found' | cut -d: -f5 | sort -u)

if [ -z "$mysigners" ]; then
	echo "# Nothing to fetch!"
else
	$GPG --batch --no-auto-check-trustdb --keyserver-options no-auto-key-retrieve "$@" --recv-keys $mysigners
	$GPG --batch --check-trustdb
fi