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

die() {
    echo 2>&1 $@
    exit 1
}

# test_one old_size new_size code
test_one() {
    go run ./mk-add-tree-request $1 $2 < test.log.key \
	| curl -s -w "%{http_code}" --data-binary @- http://localhost:7777/add-tree-head > test.rsp
    [ "$(tail -n1 test.rsp)" = $3 ] || die "Unexpected exit code for range $1, $2"
    if [ "$3" = 200 ] ; then
	grep -E '^cosignature=[0-9a-f]{64} [0-9]+ [0-9a-f]{128}$' test.rsp >/dev/null \
	    || die "cosignature missing in response"
    fi
}

test_one 0 2 200
test_one 1 2 409 # bad old size
test_one 2 4 200
test_one 4 4 200
test_one 4 5 200

# TODO: Add tests with invalid signature or proof?
