#! /bin/sh

set -e

./bin/sigsum-key generate -o test.log.key
./bin/sigsum-key generate -o test.submit.key

# Reading private key files still supports raw hex.
printf '%064x' 1 > test.token.key

# Start sigsum log server
rm -f test.log.sth
echo "startup=empty" > test.log.sth.startup
./bin/sigsum-log-primary --key-file test.log.key \
    --interval=1s --log-level=error --backend=ephemeral --sth-file test.log.sth &

SIGSUM_PID=$!

TMP_POLICY_DIR=$(mktemp -d)

cleanup () {
    kill ${SIGSUM_PID}
    rm -f "${TMP_POLICY_DIR}"/testpolicy123.sigsum-policy
    rmdir "${TMP_POLICY_DIR}"
}

trap cleanup EXIT

# Give log server some time to get ready.
sleep 2

echo "log $(./bin/sigsum-key to-hex -k test.log.key.pub) http://localhost:6965" > test.policy
echo "quorum none" >> test.policy
cp test.policy "${TMP_POLICY_DIR}"/testpolicy123.sigsum-policy

x=1
    echo >&2 "submit $x -- sigsum-submit with policy specified using -p"
    # Must be exactly 32 bytes
    printf "%31s\n" "foo-$x" \
	| ./bin/sigsum-submit --diagnostics=warning --timeout=5s \
	     --token-domain test.sigsum.org --token-signing-key test.token.key \
	     --raw-hash -o "test.$x.proof" --signing-key test.submit.key -p test.policy

x=2
    echo >&2 "submit $x -- sigsum-submit with policy specified using --policy"
    # Must be exactly 32 bytes
    printf "%31s\n" "foo-$x" \
	| ./bin/sigsum-submit --diagnostics=warning --timeout=5s \
	     --token-domain test.sigsum.org --token-signing-key test.token.key \
	     --raw-hash -o "test.$x.proof" --signing-key test.submit.key --policy test.policy

x=3
    echo >&2 "submit $x -- sigsum-submit with policy specified using -P"
    # Must be exactly 32 bytes
    printf "%31s\n" "foo-$x" \
	| SIGSUM_POLICY_DIR=${TMP_POLICY_DIR} ./bin/sigsum-submit --diagnostics=warning --timeout=5s \
	     --token-domain test.sigsum.org --token-signing-key test.token.key \
	     --raw-hash -o "test.$x.proof" --signing-key test.submit.key -P testpolicy123

x=4
    echo >&2 "submit $x -- sigsum-submit with policy specified using --named-policy"
    # Must be exactly 32 bytes
    printf "%31s\n" "foo-$x" \
	| SIGSUM_POLICY_DIR=${TMP_POLICY_DIR} ./bin/sigsum-submit --diagnostics=warning --timeout=5s \
	     --token-domain test.sigsum.org --token-signing-key test.token.key \
	     --raw-hash -o "test.$x.proof" --signing-key test.submit.key --named-policy testpolicy123

for x in $(seq 4); do
    echo >&2 "verify $x"
    printf "%31s\n" "foo-$x" \
	| ./bin/sigsum-verify --raw-hash -k test.submit.key.pub --policy test.policy "test.$x.proof"
done

# Check that the message is taken into account in validation.
if printf "%31s\n" foo-2 \
	| ./bin/sigsum-verify --key test.submit.key.pub --policy test.policy "test.1.proof" ; then
    false
else
    true
fi
