#!/bin/sh
set -e

# A simple test that runs a fakedns server that returns an A record of 127.0.0.1
# to all DNS queries. And then tries DNS queries for the name that encodes the
# PQConnect pq1 hash key. And pqconnect is expected to detect this and create a
# secure tunnel with the IP address 10.43.*. So instead of the IP address
# returned by the DNS server (127.0.0.1) it should return the address 10.43.*

dir=`dirname "$0"`

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

ip='127.0.0.1'
port=53
name='pq1tpxml7kjfchcg11kdlh7j9p6jw4zd00mcbtudcs4t0dvjgr3h4b020w020l0.pq1testdomain'

echo "running fakedns ${ip} ${port}"
${dir}/fakedns.py ${ip} ${port} 2>fakedns.log &
fakednspid=$!
sleep 1

cleanup() {
  ex=$?
  # kill fakedns
  kill -TERM "${fakednspid}" 1>/dev/null 2>/dev/null || :
  sleep 0.1
  kill -KILL "${fakednspid}" 1>/dev/null 2>/dev/null || :
  rm -f fakedns.log
  if [ "${ex}" -ne 0 ]; then
    (
      exec >&2
      set -x
      cat fakedns.log || :
      lsmod || :
      pstree || :
      systemctl status pqconnect || :
      journalctl -u pqconnect -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 DNS query
for i in `seq 1 120`; do
  result="`dig +short ${name} @${ip} || :`"
  echo "running dig +short $name @$ip: ${result}"
  if [ x"`echo ${result} | cut -d. -f1,2`" = x'10.43' ]; then
    echo 'OK'
    exit 0
  fi
  sleep 1
done

echo 'FAILED'
exit 1
