# -*-shell-script-*-
# This should be sourced by bash (though we welcome changes to make it POSIX sh compliant)

# Monkeysphere authentication add-certifier subcommand
#
# This function adds a certifier whose signatures will be used to
# calculate validity of keys used to connect to user accounts on the
# server.  The specified certifier key is first retrieved from the Web
# of Trust with the monkeysphere-user-controlled gpg_sphere keyring.
# Once then new key is retrieved, it is imported into the core
# keyring.  The gpg_core then ltsigns the key with the desired trust
# level, and then the key is exported back to the gpg_sphere keyring.
# The gpg_sphere has ultimate owner trust of the core key, so the core
# ltsigs on the new certifier key can then be used by gpg_sphere
# calculate validity for keys inserted in the authorized_keys file.
#
# This is all to keep the monkeysphere user that connects to the
# keyservers from accessing the core secret key.
#
# The monkeysphere scripts are written by:
# Jameson Rollins <jrollins@finestructure.net>
# Jamie McClelland <jm@mayfirst.org>
# Daniel Kahn Gillmor <dkg@fifthhorseman.net>
#
# They are Copyright 2008-2009, and are all released under the GPL,
# version 3 or later.

add_certifier() {

local domain=
local trust=full
local depth=1
local keyID
local importinfo
local fingerprint
local ltsignCommand
local trustval

PROMPT=true

# get options
while true ; do
    case "$1" in
	-n|--domain)
	    domain="$2"
	    shift 2
	    ;;
	-t|--trust)
	    trust="$2"
	    shift 2
	    ;;
	-d|--depth)
	    depth="$2"
	    shift 2
	    ;;
	-y)
	    PROMPT=false
	    shift 1
	    ;;
	*)
	    if [ "$(echo "$1" | cut -c 1)" = '-' ] ; then
		failure "Unknown option '$1'.
Type '$PGRM help' for usage."
	    fi
	    break
	    ;;
    esac
done

keyID="$1"
if [ -z "$keyID" ] ; then
    failure "You must specify the key ID of a key to add, or specify a file to read the key from."
fi
if [ -f "$keyID" ] ; then
    log info "Reading key from file '$keyID':"
    importinfo=$(gpg_sphere "--import" < "$keyID" 2>&1) || failure "could not read key from '$keyID'"
    # FIXME: if this is tried when the key database is not
    # up-to-date, i got these errors (using set -x):

    # ++ su -m monkeysphere -c '\''gpg --import'\''
    # Warning: using insecure memory!
    # gpg: key D21739E9: public key "Daniel Kahn Gillmor <dkg@fifthhorseman.net>" imported
    # gpg: Total number processed: 1
    # gpg:               imported: 1  (RSA: 1)
    # gpg: can'\''t create `/var/monkeysphere/gnupg-host/pubring.gpg.tmp'\'': Permission denied
    # gpg: failed to rebuild keyring cache: Permission denied
    # gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
    # gpg: depth: 0  valid:   1  signed:   0  trust: 0-, 0q, 0n, 0m, 0f, 1u
    # gpg: next trustdb check due at 2009-01-10'
    # + failure 'could not read key from '\''/root/dkg.gpg'\'''
    # + echo 'could not read key from '\''/root/dkg.gpg'\'''

    keyID=$(echo "$importinfo" | grep '^gpg: key ' | cut -f2 -d: | cut -f3 -d\ )
    if [ -z "$keyID" ] || [ $(echo "$keyID" | wc -l) -ne 1 ] ; then
	failure "There was not exactly one gpg key in the file."
    fi
else
    # get the key from the key server
    log debug "retrieving key from keyserver..."
    gpg_sphere "--keyserver $KEYSERVER --recv-key '0x${keyID}!'" || failure "Could not receive a key with this ID from the '$KEYSERVER' keyserver."
fi

export keyID

# get the full fingerprint of new certifier key
log debug "getting fingerprint of certifier key..."
fingerprint=$(gpg_sphere "--list-key --with-colons --with-fingerprint 0x${keyID}!" \
    | grep '^fpr:' | grep "$keyID" | cut -d: -f10)

if [ -z "$fingerprint" ] ; then
    failure "Key '$keyID' not found."
fi

log info "key found:"
gpg_sphere "--fingerprint 0x${fingerprint}!"

if [ "$PROMPT" = true ] ; then
    echo "Are you sure you want to add the above key as a"
    read -p "certifier of users on this system? (y/N) " OK; OK=${OK:-N}
    if [ "${OK/y/Y}" != 'Y' ] ; then
	failure "Identity certifier not added."
    fi
else
    log debug "adding key without prompting."
fi

# export the key to the core keyring so that the core can sign the
# new certifier key
log debug "exporting retrieved certifier key to core keyring..."
gpg_sphere "--export 0x${fingerprint}!" | gpg_core --import

case "$trust" in
    'marginal')
	trustval=1
	;;
    'full')
	trustval=2
	;;
    *)
	failure "Trust value requested ('$trust') was unclear (only 'marginal' or 'full' are supported)."
	;;
esac

# edit-key script to ltsign key
# NOTE: *all* user IDs will be ltsigned
ltsignCommand=$(cat <<EOF
ltsign
y
$trustval
$depth
$domain
y
save
EOF
    )

# core ltsigns the newly imported certifier key
log debug "executing core ltsign script..."
if echo "$ltsignCommand" | \
    gpg_core --quiet --command-fd 0 --edit-key "0x${fingerprint}!" ; then

    # transfer the new sigs back to the sphere keyring
    gpg_core_sphere_sig_transfer

    # update the sphere trustdb
    log debug "updating sphere trustdb..."
    gpg_sphere "--check-trustdb"

    log info "Identity certifier added."
else
    failure "Problem adding identify certifier."
fi

}