#!/bin/bash

logger -t dhcpd "Refresh dnsmasq config request"

force=$1

/opt/Eye/scripts/print-dnsmasq.pl >/tmp/mac-all
ret=$?

if [ ${ret} -ne 0 ]; then
    [ -e "/tmp/mac-all" ] && rm -f /tmp/mac-all
    logger -t dhcpd "Config generate error! Bye."
    exit
    fi

[ ! -e "/etc/dnsmasq.d/" ] && mkdir -p "/etc/dnsmasq.d/"

touch /etc/dnsmasq.d/mac-all
CHANGES=$(diff -ubBi /tmp/mac-all /etc/dnsmasq.d/mac-all | egrep "^[+-]dhcp" | awk '{ print $1 }' | sed -E 's/(\+|\-)//;s/dhcp-host=//;s/\,//' | sort -u)

if [ -n "${CHANGES}" -o -n "${force}" ]; then
    logger -t dhcpd "Update dnsmasq config"
    cat /etc/dnsmasq.d/mac-all >/tmp/mac.old
    cat  /tmp/mac-all >/etc/dnsmasq.d/mac-all
    /usr/sbin/dnsmasq --test >/dev/null 2>&1
    ret=$?
    if [ ${ret} -eq 0 ]; then
        #clear leases
        systemctl stop dnsmasq >/dev/null
        echo "${CHANGES}" | while read LEASE; do
            logger -t dhcpd "Clear ${LEASE}"
            if [ -n "${LEASE}" ]; then
                sed -i "/${LEASE}/d" /var/lib/misc/dnsmasq.leases
                fi
        done
        systemctl start dnsmasq >/dev/null
        else
        logger -t dhcpd "Config error! Rollback changes."
        cat /tmp/mac.old >/etc/dnsmasq.d/mac-all
        fi
    else
    logger -t dhcpd "Config not changed. Skip restart"
    fi

logger -t dhcpd "done"

[ -e "/tmp/mac-all" ] && rm -f /tmp/mac-all
[ -e "/tmp/mac.old" ] && rm -f /tmp/mac.old

exit
