#!/bin/bash
set -e

getpid() {
PID=$(ps x|grep stubby.yml|grep -v grep|awk '{print $1}')
}

test_stubby() {
port=$1
# a simple smoke test just make sure that at least one query can go through:
time for i in {0..9}; do
  if diff -u <(kdig +short @localhost:$port getdnsapi.net) <(echo 185.49.141.37); then
    printf .
  else
    printf !
    error=$((error+1))
  fi
  counter=$((counter+1))
done
}

error=0
counter=0
getpid
stubby -C $(dirname $0)/stubby.yml &
[ -n "$PID" ] && kill $PID
echo Test stubby started by systemd service
test_stubby 53
getpid
echo $error "time(s) error out of $counter times run."

echo
echo Test stubby started by ourselves
echo PID of stubby: $PID
test_stubby 5533
[ -n "$PID" ] && kill $PID
sleep 1
echo $error "time(s) error out of $counter times run."
[ $error -le $((counter/2)) ] && error=0
exit $error
