#!/bin/sh /etc/rc.common
START=99

local ETC_DIR="/etc/unbound/"
local VAR_DIR="/var/unbound/"
local CONF_BACK="/etc/unbound/unbound.conf.back"
local CONF_VAR="/var/unbound/unbound.conf"
local PID_VAR="/var/unbound/unbound.pid"
local CA_BUNDLE_PATH="/etc/ssl/certs/ca-certificates.crt"
local port1=5301
local port2=5302

. /lib/dnsproxy/api.sh

start() {
    pids=`ps | grep unbound | grep -v 'grep'|awk '{print $1}'`
    [ -d "$VAR_DIR" -a ${#pids} -gt 0 ] && echo "dnsproxy already exist!" >/dev/console && return
    echo "start dnsproxy_security.">/dev/console
    local doh_switch=`uci get dnsproxySecurity.dnsproxy.doh_switch`
    local dor_switch=`uci get dnsproxySecurity.dnsproxy.dor_switch`

    if [ ! -d "$VAR_DIR" -o ! -f "$CONF_VAR" ];then
        build_unbound_conf
    fi
    unbound -c $CONF_VAR
    [ "$?" -ne 0 ] && build_unbound_conf && unbound -c $CONF_VAR

    [ ! "$doh_switch" = "off" ] && {
        sed -i '$ahttps-dns#/etc/init.d/dnsproxy restart' /etc/sys_monitor.conf
        pids=`ps | grep sys_monitor | grep -v 'grep'|awk '{print $1}'`
        for pid in $pids
        do
            kill -9 $pid
        done
        [ -f /var/run/sys_monitor.pid ] && rm /var/run/sys_monitor.pid
        /etc/init.d/sys_monitor restart
    }

    [ "$dor_switch" = "on" ] && {
        add_dor_iptables 
    }

}

stop () {
    echo "stop dnsproxy_security.">/dev/console

    local pids=`pgrep https-dns-proxy`
    for pid in $pids
    do
        kill -9 $pid
    done
    [ ${#pids} -gt 0 ] && {
        [ -f "/etc/sys_monitor.conf" ] && {
            sed -i '/https-dns/d' /etc/sys_monitor.conf
            sed -i '/^$/d' /etc/sys_monitor.conf
        }

        pids=`ps | grep sys_monitor | grep -v 'grep'|awk '{print $1}'`
        for pid in $pids
        do
            kill -9 $pid
        done
        [ -f /var/run/sys_monitor.pid ] && rm /var/run/sys_monitor.pid
         /etc/init.d/sys_monitor restart
    }
    if [ -f "$PID_VAR" ]; then	
        kill -9 `cat ${PID_VAR}` && rm ${PID_VAR}
    else
        pids=`pgrep unbound`
        for pid in $pids
        do
            kill -9 $pid
        done
    fi
    [ -d "$VAR_DIR" ] && rm ${VAR_DIR} -rf

    dor_switch=`uci get dnsproxySecurity.dnsproxy.dor_switch`
    [ "$dor_switch" = "off" ] && {
        del_dor_iptables 
    }
}

restart()
{
    # fix bug1018522, sys_monitor/online_check/netifd/vpn 都存在调用 dnsproxy restart 的情况
    # 网络波动剧烈时, 出现大量 dnsproxy restart 进程示例同时存在, 占用大量内存, 优化为单进程, 合并多次 restart 动作
    ubus call dnsproxyd reload || {
        (
            flock -x 172
            stop
            start
            flock -u 172
        )172<>/etc/unbound/unbound.lock
    }
}

reload()
{
    (
        flock -x 172
        stop
        start
        flock -u 172
    )172<>/etc/unbound/unbound.lock
}
