#! /bin/sh
#
# Synchronise OpenPGP keys with key servers
# 
# Maintainer: Roland Mas <lolando@debian.org>
# Authors:
# - Roland Mas <lolando@debian.org>: initial author
# - Andrea Luzzardi (scox) <scox@scox.org>: support for ALL and --complete
#
# This program is copyright (C) 2001-2002, Roland Mas
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# History:
# - 2001-07-??  -  [Roland] First writing.  A crude shell loop.
# - 2002-07-17  -  [Scox]   Added the ALL option.
# - 2002-07-17 1.0 [Roland] Cleaned the code, added --sync and --help options.
# - 2002-07-??  -  [Scox]   Added --complete option.
# - 2002-08-21 1.1 [Roland] Fixed a few potential bugs and a bashism
# - 2002-08-27 1.2 [Roland] FIxed a few potential bugs (yes, again)

help () {
    echo "Usage: sync-keys.sh <--get | --put | --sync | --complete | --help> <key-id... | ALL>"
    exit 1
}

[ $# -lt 2 ] && help

action=$1
shift

keyids="$*"
if [ "$keyids" == "ALL" ] ; then
    keyids=$(gpg --list-keys --with-colons \
	| grep ^pub \
	| awk -F: '{ print $2 }' \
	| cut -d/ -f2 \
	| sort -u)
fi

serverlist=$(sed s/#.*// ~/.sync-keys.conf)
LC_ALL=C

get_keys () {
    for k in $keyids ; do
	for i in $serverlist ; do
	    printf "Retrieving key $k from server $i..."
	    gpg --keyserver $i --recv-keys $k > /dev/null 2>&1 && printf " OK\n" || printf " NOT OK\n"
	    done
    done
}

put_keys () {
    for k in $keyids ; do
	for i in $serverlist ; do
	    printf "Sending key $k to server $i..."
	    gpg --keyserver $i --send-keys $k > /dev/null 2>&1 && printf " OK\n" || printf " NOT OK\n"
	done
    done
}

get_sigs () {
keyids=$(gpg --list-sigs $keyids \
    | grep '^sig.*User id not found' \
    | cut -c 13-20 \
    | sort -u)
}

case $action in
    --get)
	get_keys
	;;
    --put)
	put_keys
	;;
    --sync)
	get_keys
	put_keys
	;;
    --complete)
	get_sigs
	get_keys
	;;
    *)
	help
	;;
esac
