#!/bin/sh /etc/rc.common
# Author Qier LU <lvqier@gmail.com>

START=55

gen_config_file() {
    local section="${1}"
    config_get enabled "${section}" "enabled"
    if [ ! ${enabled} ]
    then
        return
    fi
    [ ! -d /tmp/dnsmasq.d ] && mkdir -p /tmp/dnsmasq.d
    config_get ipset_name "${section}" "ipset_name"
    config_file_name="/tmp/dnsmasq.d/ipset-${ipset_name}.conf"
    rm -f "${config_file_name}"
    config_get_bool dns_forward "${section}" "dns_forward"
    if [ ${dns_forward} ]
    then
        config_get upstream_dns_server "${section}" "upstream_dns_server"
    fi
    handle_domain() {
        local domain="${1}"
        if [ ${dns_forward} ]
        then
            echo "server=/${domain}/${upstream_dns_server}" >> "${config_file_name}"
        fi
        echo "ipset=/${domain}/${ipset_name}" >> "${config_file_name}"
    }
    config_list_foreach "${section}" "managed_domain" handle_domain
}

gen_config_files() {
    rm -rf /tmp/dnsmasq.d/ipset-*.conf
    config_load 'dnsmasq-ipset'
    config_foreach gen_config_file 'ipsets'
}

start() {
    gen_config_files
}

reload() {
    gen_config_files
    /etc/init.d/dnsmasq restart
}
