#!/bin/bash

SYS_CONF="/etc/dnsmasq.conf"
BOOT_CONF="/boot/dnsmasq.conf"
USER_CONF="/data/etc/dnsmasq.conf"

CP_CONF="/etc/captive-portal.conf"

LOG="/var/log/dnsmasq.log"
PROG="/usr/sbin/dnsmasq"

test -x ${PROG} || exit 0
test -n "${OS_VERSION}" || source /etc/init.d/base
CONF=$(select_conf ${SYS_CONF} ${BOOT_CONF} ${USER_CONF})
test -s "${CONF}" || exit 0

source ${CP_CONF}


function start() {
    msg_begin "Starting dnsmasq"
    
    run_conf=/var/run/dnsmasq.conf

    # Replace placeholders
    eval "echo \"$(cat ${CONF})\"" > ${run_conf}

    ip=$(cat ${run_conf} | grep range | cut -d '=' -f 2 | cut -d '.' -f 1,2,3).1
    iface=$(cat ${run_conf} | grep interface | cut -d '=' -f 2)
    
    if [[ "${CAPTIVE_PORTAL_ENABLED}" == true ]]; then
        echo "address=/#/${ip}" >> ${run_conf}
    fi
    
    ifconfig ${iface} ${ip}

    ${PROG} -C ${run_conf} --log-facility=${LOG}
    test $? == 0 && msg_done || msg_fail
}

function stop() {
    msg_begin "Stopping dnsmasq"
    killall -q $(basename ${PROG})
    test $? == 0 && msg_done || msg_fail
}

case "$1" in
    start)
        start
        ;;
        
    stop)
        stop
        ;;
        
    restart)
        stop
        start
        ;;
    
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac
