#!/bin/sh

if test "x$KEYRING" = "x"; then
    KEYRING=/etc/entropykey/keyring
fi

usage () {
    cat <<EOF >&2
ekey-rekey: Utility to re-key an Entropy Key's Long-term-key
Usage:
    ekey-rekey SERIAL MASTERKEY
Advanced Usage:
    ekey-rekey --device SERIAL DEVICENODE MASTERKEY
EOF
}

if test "x$1" = "x"; then
    usage
    exit 1
fi

if test "x$2" = "x"; then
    usage
    exit 1
fi

if test "x$1" = "x--help"; then
    usage
    exit 0
fi

if test "x$1" = "x--version"; then
    echo "ekey-rekey version 1"
    exit 0
fi

if test "x$1" = "x--device" -o "x$1" = "x-d"; then
    DEVICE="$2"
    shift
    shift
fi

SERIAL="$1"
# alter the serial number to ensure it contains no path separators
SERIALP="$(echo "$1" | tr / _)"

: ${DEVICE="/dev/entropykey/$SERIALP"}
SOCKET="/var/run/entropykeys/$SERIALP"

NODETOUSE="$DEVICE"

shift

MASTERKEY=$(echo $@ | tr -d ' ')

if ! test -e "$DEVICE"; then
    NODETOUSE="$SOCKET"
    if ! test -e "$SOCKET"; then
	echo "Unable to find $DEVICE or $SOCKET for $SERIAL"
	exit 2
    fi
fi

ctl () {
    ekeydctl "$@" 2>/dev/null
}


# Try to ensure that any running daemon ignores the key
ctl remove "$SERIAL"
test $? = 4 && {
    echo "Unable to generate new long-term key."
    echo "Could not detach key from daemon."
    echo "Try stopping the daemon before re-running the rekey tool."
    exit 4
}

# Generate the new key
ekey-setkey -s "$SERIAL" -m "$MASTERKEY" -f "$KEYRING" "$NODETOUSE"
if test $? -ne 0; then
    echo "Unable to generate new long-term key"
fi

# Re-add the new keyring
ctl keyring "$KEYRING"

# Add the new key and hope for the best
ctl add "$NODETOUSE"
