#! /bin/sh

set -e

./bin/sigsum-key gen -o test.log.key
./bin/sigsum-key gen -o test.witness.key

# Start witness server
rm -f test.witness.cth
./bin/sigsum-witness -k test.witness.key --log-key test.log.key.pub \
  --state-file test.witness.cth localhost:7777 &

WITNESS_PID=$!

cleanup () {
    kill ${WITNESS_PID}
}

trap cleanup EXIT

# Give server some time to start
sleep 1

curl -s http://localhost:7777/get-tree-size/$(./bin/sigsum-key hash -k test.log.key.pub) > test.rsp

[ "size=0" = "$(cat test.rsp)" ] || (
    echo 1>&2 Unexpected response
    exit 1
)

curl -s -w '%{http_code}\n' http://localhost:7777/get-tree-size/x > test.rsp

[ "400" = "$(tail -1 test.rsp)" ] || (
    echo 1>&2 'Unexpected status code, expected 400 (Bad request)'
    exit 1
)

curl -s -w '%{http_code}\n' http://localhost:7777/get-tree-size/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa > test.rsp

[ "404" = "$(tail -1 test.rsp)" ] || (
    echo 1>&2 'Unexpected status code, expected 404 (Not found)'
    exit 1
)
