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

# Monkeysphere host import-key subcommand
#
# 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-2010 and are all released under the GPL,
# version 3 or later.

import_key() {

local keyFile="$1"
local serviceName="$2"

# check that key file specified
if [ -z "$keyFile" ] ; then
    failure "Must specify key file to import, or specify '-' for PEM-encoded RSA key on stdin."
fi

# fail if hostname not specified
if [ -z "$serviceName" ] ; then
    failure "You must specify a service name for use in the OpenPGP certificate user ID."
fi

# test that a key with that user ID does not already exist
prompt_userid_exists "$serviceName"

# check that the service name is well formatted
check_service_name "$serviceName"

# create host home
mkdir -p "${MHDATADIR}"
mkdir -p "${GNUPGHOME_HOST}"
chmod 700 "${GNUPGHOME_HOST}"

key_type_from_file() {
    # translates from OpenSSH's pubkey format string to GnuPG's
    # Key-Type parameter:
    local keyType
    if keyType=$(ssh-keygen -y -f "$keyFile" | awk '{ print $1 }'); then
        case "$keyType" in
            ssh-dss)
                echo DSA
                ;;
            ecdsa-sha2-nistp256)
                echo ECDSA
                ;;
            ssh-ed25519)
                echo EDDSA
                ;;
            ssh-rsa)
                echo RSA
                ;;
            *)
                log error "unknown key type '$keyType' from file '$keyFile'"
                return 1
                ;;
        esac
    else
        log error "ssh-keygen could not interpret '$keyFile'"
        return 1
    fi
    return 0
}


if [ "$keyFile" = '-' ] ; then
    # import PEM-encoded RSA stdin to an OpenPGP private key
    log verbose "importing PEM-encoded RSA key from stdin..."
    PEM2OPENPGP_USAGE_FLAGS=authenticate pem2openpgp "$serviceName" \
	| gpg_host --import
else
    # import some sort of file that OpenSSH's keygen can handle
    if keyType=$(key_type_from_file "$keyFile"); then
        # we lock to avoid concurrent interactions with gpg-agent and
        # the sshcontrol file would be dubious
        lock create "$GNUPGHOME_HOST/importlock"
        if test -e "$GNUPGHOME_HOST/sshcontrol" && grep -q '^[0-9A-F]' "$GNUPGHOME_HOST/sshcontrol"; then
            backupSshControl=$(mktemp "$GNUPGHOME_HOST/sshcontrol.XXXXXXXX")
            log error "$GNUPGHOME_HOST/sshcontrol already contained a key, backing up to $backupSshControl"
            mv -f "$GNUPGHOME_HOST/sshcontrol" "$backupSshControl"
        fi
        
        log verbose "importing $keyType key from file '$keyFile'..."
        if ! { test -e "$GNUPGHOME_HOST/gpg-agent.conf" && grep -Fxq batch "$GNUPGHOME_HOST/gpg-agent.conf" ; }; then
            echo batch >> "$GNUPGHOME_HOST/gpg-agent.conf"
            GNUPGHOME="$GNUPGHOME_HOST" gpgconf --reload gpg-agent
            GNUPGHOME="$GNUPGHOME_HOST" gpgconf --launch gpg-agent
        fi
        SSH_AUTH_SOCK=$(GNUPGHOME="$GNUPGHOME_HOST" gpgconf --list-dirs agent-ssh-socket) ssh-add "$keyFile"
        if keyGrip=$(awk '/^[0-9A-F]/{print $1}' < "$GNUPGHOME_HOST/sshcontrol") &&
           test -n "$keyGrip" && [ $(wc -l <<<"$keyGrip") -eq 1 ] ; then
            gpg_host --batch --full-generate-key <<EOF
Key-Type: $keyType
Key-Grip: $keyGrip
Key-Usage: auth
Name-Real: $serviceName
%no-protection
%commit
EOF
        else
            rm -f "$GNUPGHOME_HOST/sshcontrol"
            lock remove "$GNUPGHOME_HOST/importlock"
            failure "did not find a single keygrip in $GNUPGHOME_HOST/sshcontrol during import"
        fi
        rm -f "$GNUPGHOME_HOST/sshcontrol"
        lock remove "$GNUPGHOME_HOST/importlock"
    else
        log error "falling back to pem2openpgp (which will probably still fail)..."
        PEM2OPENPGP_USAGE_FLAGS=authenticate pem2openpgp "$serviceName" \
	                       <"$keyFile" \
	    | gpg_host --import
    fi
fi

# export to OpenPGP public key to file
update_pgp_pub_file

log info "host key imported:"

# show info about new key
show_key "$serviceName"

}
