#!/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 {-d | --device} DEVICENODE SERIAL MASTERKEY
    ekey-rekey --device=DEVICENODE SERIAL MASTERKEY
EOF
}

optloop=1
while test $optloop = 1; do
    case x$1 in
    x-d|x--device)
	DEVICE=$2
	shift
	shift
	;;
    x--device=*)
	DEVICE=$(echo "x$1" | sed 's/^x--device=//')
	shift
	;;
    x-h|x-\?|x--help)
	usage
	exit 0
	;;
    x-V|x--version)
	echo "ekey-rekey version 1"
	exit 0
	;;
    x--)
	shift
	break
	;;
    x|x-*)
	# empty or unknown -o or unknown --long-option
	usage
	exit 1
	;;
    *)
	# non-option argument
	optloop=0
	;;
    esac
done

if test $# -ne 2; then
    usage
    exit 1
fi

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

DEVPATHS=""

if test "x" != "x$DEVICE"; then
    DEVPATHS="$DEVICE "
fi

DEVPATHS="${DEVPATHS}/dev/entropykey/$SERIALD /dev/entropykey/$SERIALU /var/run/entropykeys/$SERIALD /var/run/entropykeys/$SERIALU"

shift

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

for DEVPATH in $DEVPATHS; do
    if test -e "$DEVPATH"; then
        NODETOUSE="$DEVPATH"
    fi
done

if test "x" = "x$NODETOUSE"; then
    echo >&2 "Unable to find any device node or socket for $SERIAL"
    echo >&2 "Looked in: $DEVPATHS"
    exit 2
fi

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


# Try to ensure that any running daemon ignores the key
ctl remove "$SERIAL"
test $? = 4 && {
    echo >&2 "Unable to generate new long-term key."
    echo >&2 "Could not detach key from daemon."
    echo >&2 "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 >&2 "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"
