#!/bin/sh -e

VERBOSE=yes
log()
{
    if test $1 != debug || expr "$VERBOSE" : "[yY]" > /dev/null; then
	logger -p user.$1 -t "xs-tools[$$]" -- "$2"
    fi
}

log debug "Looking to import trusted keys"

# get TRUSTED_KEYS_DIR, USB_TRUSTED_KEYS_DIR, and CHECK_SIGS_FLAG
. /etc/xs-tools.conf

USB_KEY_DIR="$UM_MOUNTPOINT/$USB_TRUSTED_KEYS_DIR"

# If the directory isn't there, then exit.  This usb drive is not for us.
[ -d $USB_KEY_DIR ] || exit 0

log notice "Found $USB_KEY_DIR, will try import"

TEMPDIR=$(mktemp -d)
GOOD_KEYS_DIR=$(mktemp -d)

# combined with set -e, error() is called if something fails.
error(){
    rm -rf $TEMPDIR $GOOD_KEYS_DIR
    logger -p user.err -t "xs-otp-publish[$$]" "Error at line $(caller)"
}
trap error ERR


# copy first to a temporary firectory, so any USB read errors don't
# leave $TRUSTED_KEYS_DIR in a messed up state.

umask 0133
for f in $USB_KEY_DIR/*; do
    cp $f $TEMPDIR
done

log notice "Copied keys from USB disk to temporary directory..."

# If there are no known keys, copy in the new ones regardless of security.
# otherwise:
#  If security is off, do nothing.
#  If there are existing trusted keys, they must sign this one.

if [ -d $TRUSTED_KEYS_DIR ] && [ "`ls $TRUSTED_KEYS_DIR`" ] ; then
    if ! [[ -e $CHECK_SIGS_FLAG ]] ; then
        # this branch is not strictly necessary (xs-check --strict
        # tests the same thing), but it will make the logs explicable.
        log notice "Key checking is not enabled, but keys exist"
        log notice "The new keys are not being imported"
    else
        #Check that new keys are signed by an existing one
        for f in $TEMPDIR/*; do
            if [[ ${f: -4} != '.sig' ]]; then
                log debug "checking $f"
                if xs-check -q --strict $f ; then
                    mv $f $GOOD_KEYS_DIR
                else
                    log warn "$f.sig is not a known valid signature for $f."
                fi
            fi
        done
    fi
else
    #Trust totally. This behaviour may not last.
    log warn "TRUSTING new keys because we have none to check them against"
    if ! [[ -e $CHECK_SIGS_FLAG ]]; then
        log warn "$CHECK_SIGS_FLAG does not exist"
    fi
    for f in $TEMPDIR/*; do
        if [[ ${f: -4} != '.sig' ]]; then
            mv $f $GOOD_KEYS_DIR
        fi
    done
fi


if [[ "`ls $GOOD_KEYS_DIR`" ]]; then
    mkdir -p -m 755 $TRUSTED_KEYS_DIR
    for f in $GOOD_KEYS_DIR/*; do
        log notice "installing key `basename $f`"
        mv $f $TRUSTED_KEYS_DIR
    done
fi

rm -rf $TEMPDIR $GOOD_KEYS_DIR


log notice "Finished importing keys to $TRUSTED_KEYS_DIR"

#XXX not checking that the keys are any good.

