#!/bin/sh
# vim:ts=4:sw=4
# $Id: keysign.sh,v 1.2 2003/07/24 05:41:23 jaqque Exp $

# (c) Copyright 2003 John H. Robinson, IV <jaqque@debian.org>
# Distributed under the terms of the GNU GPL version 2.

# if you use this script, you will want to change the From: address

# TODO:
#   command line options!
#   help
#   make it easier to override the From: address
#   snarf public keys from default keyring instead of using a keyserver

# KEYSERVERS - list of keyservers to query
# secret - list of secretkeys to sign with
# self - secret key to _also_ encrypt the signed key to
# TEMP - temporary directory to use
# TMP - temporary directory to use (overrides TEMP)

KEYSERVERS=${KEYSERVERS:-"subkeys.pgp.net wwwkeys.eu.pgp.net search.keyserver.net wwwkeys.pgp.net pgp5.ai.mit.edu pgp.mit.edu. wwwkeys.kernel-panic.org keyring.debian.org"}

getkey () {
	while [ $1 ]
	do
		for keyserver in $KEYSERVERS
		do
			echo Querying keyserver $keyserver
			gpg $gpg_opts $master --keyserver $keyserver --recv-key $1
		done
		shift
	done
}

gpg_pub () {
	gpg $gpg_opts --with-colons --list-keys "$@" | grep '^pub:' | cut -d: -f10
}

gpg_sec () {
	gpg $gpg_opts --fast-list-mode --with-colons --list-secret "$@" | grep '^sec:' | cut -d: -f5
}

header () {
cat <<EOF
From: "John H. Robinson, IV" <jaqque@debian.org>
Subject: Your Key
X-Script-Version: $Revision: 1.2 $

Please find attached your signed key. If you have any problems with it, do
not hesitate to let me know.

This key was sent to you, and only to you. The original signed keys have
been deleted; you have the only copy. You may import this to your keyring,
and export it to key servers around the world at your discretion.

This is an automatic mailing.

-john


EOF
}

#set up the working directory. use the value of TMP, TEMP, or fallback to /tmp
tmp=/tmp
tmp=${TEMP:-$tmp}
tmp=${TMP:-$tmp}

while [ $1 ]; do
	tmpdir=$tmp/$1.$$
	mkdir $tmpdir || exit 1
	cd $tmpdir || exit 1

	# get requested key
	gpg_opts="--no-default-keyring"
	master="--keyring $tmpdir/$1.pub"
	getkey $1

	# copy in public part of secret keys
	secret=${secret:-`gpg_sec $master`} # yes, this works!
	for key in $secret ; do
		self=${self:-$key} # set $self to the first secret key
		echo adding $key
		gpg --export $key | gpg $gpg_opts $master --import
	done

	uid=`gpg $gpg_opts $master --list-key $1 2>/dev/null | sed -ne's/.*<\([^>]*\)>.*/\1/p' | sort | uniq`

	for i in $uid; do
		cp $1.pub $1-$i.pub
		keyring="--keyring $tmpdir/$1-$i.pub"
		#echo secret is \"$secret\"
		for j in $secret; do
			echo
			echo Signing key $i with `gpg_pub $keyring --list-key $j`
			gpg $gpg_opts $keyring --default-key $j --edit-key $1 2>/dev/null
		done # j in $secret
		gpg $gpg_opts $keyring --export $1 | gpg $gpg_opts $keyring --armor --recipient $1 --encrypt-to $self --output $i.asc --encrypt
		(header; cat $i.asc) | mail -t $i
	done # i in $uid

	cd /
	rm -rf $tmpdir

	shift
done # while [ $1 ]
