#!/bin/sh
# clean_keyring.sh - clean up all the excess keys

# origin: https://scruss.com/blog/2013/05/12/clean-up-your-gnupg-keyring/

set -e

# 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=$($GPG --batch --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 who have signed my key
mysigners=$($GPG --batch --list-sigs --with-colons $mykeys | grep '^sig' | cut -d: -f5 | sort -u)

# keep all of the signers, plus my key (if I haven't self-signed)
keepers=$(echo $mykeys $mysigners | tr ' ' '\012' | sort -u)

# the keepers list in egrep syntax: ^(key|key|…)
keepers_egrep=$(echo $keepers | sed 's/^/^(/; s/$/)/; s/ /|/g;')

# everyone who isn't on the keepers list is deleted
deleters=$($GPG --batch --list-keys --with-colons | grep '^pub' | cut -d: -f5 | egrep -v ${keepers_egrep})

if [ -z "$deleters" ]; then
	echo "# Nothing to delete!"
else
	$GPG "$@" --delete-keys $deleters
# TODO: use below instead when --force
#	$GPG --batch --yes "$@" --delete-keys $deleters
fi