#!/bin/sh
set -e

dir=`dirname "$0"`

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

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

echo 'loading tun kernel module'
modprobe tun || :

if [ ! -e /dev/net/tun ]; then
  echo '/dev/net/tun does not exist, skipping test' >&2
  exit 77
fi

timeout=30
echo "initial sleep ${timeout} seconds"
sleep "${timeout}"

for timeout in 1 3 11 45; do
  echo "sleeping ${timeout} seconds"
  sleep "${timeout}"
  systemctl is-active pqconnect-server.service && break
  if [ x"${timeout}" = x45 ]; then
    echo 'systemd service pqconnect-server.service not running' >&2
    exit 1
  fi
done

echo 'trying to download long-term key'
"${dir}/pqconnect-server-keyserver.py"

echo 'ok'
exit 0
