#!/bin/sh /etc/rc.common
#

START=50
USE_PROCD=1

EXTRA_COMMANDS="suspend resume query status"
EXTRA_HELP="	suspend	Suspend adblock processing
	resume	Resume adblock processing
	query	<DOMAIN> Query active blocklists for specific domains
	status	Print runtime information"

adb_init="/etc/init.d/adblock"
adb_script="/usr/bin/adblock.sh"

boot()
{
    adb_boot=1
    ubus -t 30 wait_for network.interface 2>/dev/null
    rc_procd start_service
}

start_service()
{
    if [ $("${adb_init}" enabled; printf ${?}) -eq 0 ]
    then
        if [ -n "${adb_boot}" ]
        then
            return 0
        fi
        procd_open_instance "adblock"
        procd_set_param command "${adb_script}" "${@}"
        procd_set_param stdout 1
        procd_set_param stderr 1
        procd_close_instance
    fi
}

stop_service()
{
    rc_procd "${adb_script}" stop
    rc_procd start_service
}

restart()
{
    rc_procd start_service restart
}

suspend()
{
    rc_procd "${adb_script}" suspend
}

resume()
{
    rc_procd "${adb_script}" resume
}

query()
{
    rc_procd "${adb_script}" query "${1}"
}

status()
{
    rc_procd "${adb_script}" status
}

service_triggers()
{
    local iface="$(uci -q get adblock.global.adb_iface)"
    local delay="$(uci -q get adblock.global.adb_triggerdelay)"

    PROCD_RELOAD_DELAY=$((${delay:=2} * 1000))
    for name in ${iface}
    do
        procd_add_interface_trigger "interface.*.up" "${name}" "${adb_init}" start
    done
    PROCD_RELOAD_DELAY=1000
    procd_add_config_trigger "config.change" "adblock" "${adb_init}" start
}
