#!/bin/sh
set -e

# A simple test that receives the hash of the public key from the keyserver.
# And it compares it with a hash calculated from the key that is stored in the
# /etc/pqconnect/keys directory.

# debian/tests directory
dir=`dirname "$0"`

# change directory to $AUTOPKGTEST_TMP
cd "${AUTOPKGTEST_TMP}"

cleanup() {
  ex=$?
  if [ "${ex}" -ne 0 ]; then
    (
      exec >&2
      set -x
      lsmod || :
      pstree || :
      systemctl status pqconnect-server || :
      journalctl -u pqconnect-server -x --no-tail --no-pager || :
    )
  fi
  exit "${ex}"
}
trap "cleanup" EXIT TERM INT

# try to load `tun` module, and check if exist
modprobe tun || :
if [ ! -e /dev/net/tun ]; then
  echo '/dev/net/tun does not exist, skipping test' >&2
  exit 77
fi

# send query to keyserver
for i in `seq 1 120`; do
  keyserverip=127.0.0.1
  keyserverport=`cat /etc/pqconnect/config/keyport || :`
  filesystemhash="`cat /etc/pqconnect/keys/mceliece_pk /etc/pqconnect/keys/x25519_pk | ${dir}/hash.py`"
  keyserverhash="`${dir}/keyserver-query.py -t1 -p0 -l0 127.0.0.1 ${keyserverport}`"
  echo "try ${i}:"
  echo "debug: keyserverip  = ${keyserverip}"
  echo "debug: keyserverport  = ${keyserverport}"
  echo "debug: filesystemhash = ${filesystemhash}"
  echo "debug: keyserverhash  = ${keyserverhash}"
  if [ x"${keyserverhash}" = x"${filesystemhash}" ]; then
    echo 'OK'
    exit 0
  fi
done
echo 'FAILED' >&2
exit 1
