#!/bin/bash -ex

PID_FILE="/tmp/test_dnsmasq.pid"
LEASE_FILE="/tmp/test_dnsmasq.lease"
IPV4_BLOCK="192.0.2"
DHCP_SRV_IP="${IPV4_BLOCK}.1"
DHCP_CLI_IP="${IPV4_BLOCK}.99"
DNS_SERVER1="1.1.1.1"
DNS_SERVER2="8.8.8.8"
DHCPCLI_MAC="72:d0:16:c6:80:5f"
ETH2_MAC="72:d0:16:c6:80:5e"

if [ -e $PID_FILE ];then
    kill `cat $PID_FILE`
fi

ip link del dhcpcli || true
ip netns del mozim || true
nmcli c del dhcpcli || true

ip netns add mozim
ip link add dhcpcli type veth peer name dhcpsrv
ip link set dhcpcli address $DHCPCLI_MAC
ip link set dhcpcli up
ip link set dhcpsrv netns mozim
ip netns exec mozim ip link set dhcpsrv up
ip netns exec mozim ip addr add ${DHCP_SRV_IP}/24 dev dhcpsrv
rm $LEASE_FILE -f
ip netns exec mozim dnsmasq \
    --pid-file=$PID_FILE \
    --log-dhcp \
    --conf-file=/dev/null \
    --dhcp-leasefile=$LEASE_FILE \
    --no-hosts \
    --dhcp-host=${DHCPCLI_MAC},${DHCP_CLI_IP} \
    --dhcp-option=option:dns-server,$DNS_SERVER1 \
    --dhcp-option=option:domain-name,example.com \
    --dhcp-option=option:ntp-server,${DHCP_SRV_IP} \
    --clear-on-reload \
    --interface=dhcpsrv \
    --enable-ra \
    --dhcp-range=${IPV4_BLOCK}.2,${IPV4_BLOCK}.50,2m \
    --no-ping

nmcli c add type ethernet ifname dhcpcli connection.id dhcpcli \
    ipv4.method auto ipv6.method ignore

nmcli c up "dhcpcli"
sleep 2
grep $DNS_SERVER1 /etc/resolv.conf
./device-reapply.py dhcpcli ${DHCP_CLI_IP}
sleep 5
kill `cat $PID_FILE`
sleep 1

ip netns exec mozim dnsmasq \
    --pid-file=$PID_FILE \
    --log-dhcp \
    --conf-file=/dev/null \
    --dhcp-leasefile=$LEASE_FILE \
    --no-hosts \
    --dhcp-host=${DHCPCLI_MAC},${DHCP_CLI_IP} \
    --dhcp-option=option:dns-server,$DNS_SERVER2 \
    --dhcp-option=option:domain-name,example.com \
    --dhcp-option=option:ntp-server,${DHCP_SRV_IP} \
    --clear-on-reload \
    --interface=dhcpsrv \
    --enable-ra \
    --dhcp-range=${IPV4_BLOCK}.2,${IPV4_BLOCK}.50,2m \
    --no-ping

sleep 2m

grep $DNS_SERVER2 /etc/resolv.conf || echo "Busted"
