#! /bin/sh
#
# gpg-mailkeys: mail out just signed keys to their owners
#

set -e

VERSION=''

# Define the charset used in the text message of the mail
LOCAL_CHARSET=""

##
# Get the local charset.
#
# The local charset is deduced from the charset used by both ~/.gpg-mailkeysrc
# and ~/.signature. If none of these files exist, the local charset is assumed
# to be us-ascii.

get_local_charset ()
{
    local charset="us-ascii"
    local file_list="$HOME/.signature $HOME/.gpg-mailkeysrc"

    for filename in $file_list; do

        if [ -e $filename ]; then
            charset=`file --mime-encoding $filename | cut -d ' ' -f 2`
            break
        fi

    done;

    LOCAL_CHARSET=$charset
}

if [ -z "$*" ]; then
	printf "Send people their newly signed GPG key by mail.\n"
	printf "Usage: $0 keyid ...\n"
	exit 1
fi

if [ -e ~/.gpg-mailkeysrc ] ; then
	. ~/.gpg-mailkeysrc
fi
if [ -n "$EMAIL" ]; then
	FROM="$EMAIL"
fi
if [ -z "$FROM" ]; then
       echo "Error: No EMAIL set in ~/.gpg-mailkeysrc and no FROM set in environment."
       exit 1
fi
if [ -z "$SUBJECT" ]; then
	SUBJECT="Your signed GPG key"
fi
if [ -z "$NAME" ]; then
	NAME=`getent passwd $USER | cut -d: -f5 | cut -d, -f1`
fi
if [ -z "$TEXT" ]; then
	TEXT="Hi,

Here is your signed GPG key.

Enjoy,
$NAME"
fi

get_local_charset

FAILKEYS=

while [ -n "$1" ]; do
	printf "[$1] "
	TEMPFILE=`mktemp -t gpg2mail.XXXXXX`
	ADDR=`${GNUPGBIN:-gpg} --with-colons --fixed-list-mode --list-key $1 | sed -e 's/^uid:[^rei:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:\([^:<]*<[^:>]*>\):.*/@@uid@@ \1/' -e '/^@@uid@@ /!d' -e 's/([^)]*)//g' -e 's/  */ /g' -e 's/^@@uid@@ //' | head -1`
	if [ -z "$ADDR" ]; then
		printf "(no usable user ids)\n"
		FAILKEYS="$FAILKEYS:$1"
		shift 1
		continue
	fi
	NANOTIME=`date +%s-%N`
	BOUNDARY="ksp-$$-boundary-$NANOTIME"
	
	printf "$ADDR:"
	printf >$TEMPFILE "From: $NAME <$FROM>\n"
cat << EOM >> $TEMPFILE
To: $ADDR
Subject: $SUBJECT
User-Agent: gpg-mailkeys/$VERSION
MIME-Version: 1.0
Content-Type: multipart/mixed; micalg=pgp-sha1;
    boundary="$BOUNDARY"
Content-Disposition: inline



--$BOUNDARY
Content-Type: text/plain; charset=$LOCAL_CHARSET
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable
 

`echo "$TEXT" | qprint -e`

EOM

if [ -f ~/.signature ]; 
	then printf -- "--=20\n" >> $TEMPFILE 
	qprint -e ~/.signature >> $TEMPFILE
fi

cat << EOM >> $TEMPFILE

--$BOUNDARY
Content-Type: application/pgp-keys
Content-Disposition: attachment; filename="$1.asc"

`${GNUPGBIN:-gpg} --armor --export $1`

--$BOUNDARY--
EOM
	printf " sending"
	${SENDMAIL:-/usr/sbin/sendmail} $SENDMAIL_ARGS -ti <$TEMPFILE
	rm $TEMPFILE
	printf " done.\n"
	shift 1
done

if [ -n "$FAILKEYS" ]; then
	printf "\nNote: The following keys could not be sent:\n"
	printf "$FAILKEYS\n" | tr ':' '\n' | sed -e '/^ *$/d' -e 's/^/  /'
fi
