#!/bin/sh
#Copyright (c) 2003-2006 Peter Palfrader <weasel@debian.org>
#Copyright (c) 2007 Alexander Wirt <formorer@debian.org>
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of
#this software and associated documentation files (the "Software"), to deal in
#the Software without restriction, including without limitation the rights to
#use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
#of the Software, and to permit persons to whom the Software is furnished to do
#so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.

set -e

# LANG=C
# LC_ALL=C

export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"

rcfile=$HOME/.pkkrc

if [ ! -f $rcfile ]
then
    echo >&2 "File $rcfile missing."
    exit 1
fi

. $rcfile

if [ ! -f "$PKKHEADERFILE" ]
then
    echo >&2 "PKKHEADERFILE unset and/or '$PKKHEADERFILE' is not a file.  Set it in $rcfile."
    exit 1
fi

if [ -d "$GNUPGHOME" ]
then
    echo -n "Remove '$GNUPGHOME'? [Y/n] > "
    read r
    [ n = "$r" ] && echo "OK, aborting." && exit 0
    rm -rf $GNUPGHOME
else
    echo >&2 "GNUPGHOME unset and/or '$GNUPGHOME' is not a directory.  Set it (and be sure to export it), e.g. in $rcfile."
    exit 1
fi

mkdir $GNUPGHOME
chmod go-rwx $GNUPGHOME

keysdir=$KSP_HOMEDIR/keys/$PKK_HOST/keys

if [ -d "$keysdir" ]
then
    ls -1t $keysdir/* | xargs gpg -q --import
else
    echo >&2 "KSP_HOMEDIR and/or PKK_HOST unset and/or '$keysdir' is not a directory.  Set it in $rcfile."
    exit 1
fi

if [ ! "$KSPFILE" ]
then
    echo >&2 "KSPFILE unset.  Set it in $rcfile."
    exit 1
fi

(
d=$( date --rfc-3339=seconds )
echo "Generated $d using pkk-generate-list as shipped with"
echo "pgp-kspkeyserver (http://mdcc.cx/pgp-kspkeyserver/)."

cat $PKKHEADERFILE

gpg -q --no-options --fingerprint --list-key |
	grep -v '^sub ' |
	perl -npe '$c = sprintf("%03d", ++$C); s/^pub/$c  [ ] Fingerprint OK        [ ] ID OK\npub/m or $C--' |
	grep -v '^uid.*jpeg image of size' |
	sed -e 's/^uid\s*/uid /' |
	sed -e 's/^$/--------------------------------------------------------------------------------\n/' |
	tail -n +3
) > $KSPFILE

gpg -q --no-options --armor --export --export-options export-clean | bzip2 > ${KSPFILE%.txt}.keyring.asc.bz2

echo "Generated files $KSPFILE*."
echo "Don't forget to generate and publish a detached signature too!"
echo "Run: gpg --detach-sign --armor $KSPFILE"

