#!/bin/bash -e

CURDIR=$(pwd)
GROUP=$(id -g -n)
DNSPORT=5353
IPV4PREFIX='192.168.21'
MAXTXT=100

function exit_handler()
{
    if test -f "$AUTOPKGTEST_TMP/dnsmasq.pid"; then
	kill -TERM $(cat "$AUTOPKGTEST_TMP/dnsmasq.pid") || true
    fi
    sleep 1;
    if test -f "$AUTOPKGTEST_ARTIFACTS/dnsmasq.log"; then
	cat "$AUTOPKGTEST_ARTIFACTS/dnsmasq.log"
    fi
}
trap exit_handler EXIT


tee $AUTOPKGTEST_TMP/dnsmasq-hosts.conf <<EOF
$IPV4PREFIX.19    dns dhcp
$IPV4PREFIX.238    proxy wpad
$IPV4PREFIX.253    switch
$IPV4PREFIX.254    gwdij
EOF

tee  $AUTOPKGTEST_TMP/dnsmasq.conf.base <<EOF
#### DNS ####
domain-needed
# forwarders
server=8.8.8.8
# A and AAAA
addn-hosts=$AUTOPKGTEST_TMP/dnsmasq-hosts.conf
expand-hosts
domain=test
port = $DNSPORT
user = $USER
group = $GROUP

log-facility=$AUTOPKGTEST_ARTIFACTS/dnsmasq.log
log-queries

log-dhcp
dhcp-alternate-port = 1067, 1068
dhcp-range=$IPV4PREFIX.20,$IPV4PREFIX.50,12h
dhcp-option=option:netmask,255.255.255.0
dhcp-option=option:router,$IPV4PREFIX.254
dhcp-option=option:dns-server,$IPV4PREFIX.254
dhcp-option=option:ntp-server,$IPV4PREFIX.254
dhcp-option=option:domain-name,test
dhcp-host=2c:27:d7:01:71:08,$IPV4PREFIX.111
txt-record=test,example0000=example0000
EOF

cp $AUTOPKGTEST_TMP/dnsmasq.conf.base $AUTOPKGTEST_TMP/dnsmasq.conf

dnsmasq --conf-file="$AUTOPKGTEST_TMP/dnsmasq.conf" --pid-file="$AUTOPKGTEST_TMP/dnsmasq.pid"

# add step by step TXT records
record="txt-record=test"
for i in $(seq 1 $MAXTXT)
do
    cp -f $AUTOPKGTEST_TMP/dnsmasq.conf.base $AUTOPKGTEST_TMP/dnsmasq.conf
    record=$record,$(printf 'example%04i=%04i' $i $i)
    echo "$record" >> "$AUTOPKGTEST_TMP/dnsmasq.conf"
    tail "$AUTOPKGTEST_TMP/dnsmasq.conf"
    kill -TERM $(cat $AUTOPKGTEST_TMP/dnsmasq.pid)
    sleep 1
    dnsmasq --conf-file="$AUTOPKGTEST_TMP/dnsmasq.conf" --pid-file="$AUTOPKGTEST_TMP/dnsmasq.pid"
    sleep 1
    echo '--------------------------------------------------------------------'
    dig +short @localhost  -p $DNSPORT TXT test
    dig @localhost  -p $DNSPORT TXT test
    echo '--------------------------------------------------------------------'
done



