#! /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=$!

cleanup () {
    kill ${SIGSUM_PID}
}

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

for x in $(seq 5); do
    echo "foo-$x" > "test.$x.msg"
done

rm -f test.*.req
rm -f test.*.proof

./bin/sigsum-submit -k test.submit.key --diagnostics=warning test.1.msg test.2.msg test.3.msg test.4.msg test.5.msg

./bin/sigsum-submit -p test.policy --diagnostics=warning --timeout=5s \
  --token-domain test.sigsum.org --token-signing-key test.token.key \
  test.1.msg.req test.2.msg.req test.3.msg.req test.4.msg.req test.5.msg.req

for x in $(seq 5); do
    echo >&2 "verify $x"
    ./bin/sigsum-verify < "test.$x.msg" --key test.submit.key.pub --policy test.policy "test.$x.msg.proof"
done

# Check that the message is taken into account in validation.
if ./bin/sigsum-verify < test.2.msg --key test.submit.key.pub --policy test.policy "test.1.msg.proof" ; then
    false
else
    true
fi
