#!/bin/sh

set -e

# this helps with running the test outside of the autopkgtest environment
if [ -z "${AUTOPKGTEST_TMP:-}" ]; then
  AUTOPKGTEST_TMP="$(mktemp -d --suffix=.autopkgtest)"
fi

# certspotter uses these to override the default ~/.certspotter path.
# We use the environment variables (rather than -watchlist and -state_dir)
# in our systemd service, so it's better to test with these for parity
export CERTSPOTTER_CONFIG_DIR=$AUTOPKGTEST_TMP/certspotter-cfg
export CERTSPOTTER_STATE_DIR=$AUTOPKGTEST_TMP/certspotter

mkdir $CERTSPOTTER_CONFIG_DIR $CERTSPOTTER_STATE_DIR

# monitor all domains - this should always have traffic
echo '.' > $CERTSPOTTER_CONFIG_DIR/watchlist

# initialize the certspotter database, starting at the end
#
# pass -no_save, as otherwise the output can be several hundred megabytes
# (depending on the timing)
certspotter -no_save -start_at_end

# flaky, likely due to piping
rm -f $CERTSPOTTER_STATE_DIR/lock

# give some time for the CT logs to advance; typically a second's worth of logs
# contains multiple hundred entries
sleep 1

# now check for at least one logged certificate
certspotter -no_save -start_at_end | grep -q Pubkey
