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

START=30
USE_PROCD=1

EXTRA_COMMANDS="suspend resume query report"
EXTRA_HELP="	suspend	Suspend adblock processing
	resume	Resume adblock processing
	query	<DOMAIN> Query active blocklists for specific domains
	report	<SEARCH> Print dns query statistics with an optional search parameter"

adb_init="/etc/init.d/adblock"
adb_script="/usr/bin/adblock.sh"
adb_pidfile="/var/run/adblock.pid"

if [ -s "${adb_pidfile}" ] && { [ "${action}" = "start" ] || [ "${action}" = "stop" ] || \
	[ "${action}" = "restart" ] || [ "${action}" = "reload" ] || [ "${action}" = "report" ] || \
	[ "${action}" = "suspend" ] || [ "${action}" = "resume" ] || [ "${action}" = "query" ]; }
then
	exit 0
fi

boot()
{
	[ -s "${adb_pidfile}" ] && > "${adb_pidfile}"
	rc_procd start_service
}

start_service()
{
	if [ "$("${adb_init}" enabled; printf "%u" ${?})" -eq 0 ]
	then
		if [ "${action}" = "boot" ]
		then
			if [ "$(uci_get adblock global adb_trigger)" != "timed" ]
			then
				return 0
			fi
		fi
		procd_open_instance "adblock"
		procd_set_param command "${adb_script}" "${@}"
		procd_set_param pidfile "${adb_pidfile}"
		procd_set_param nice "$(uci_get adblock extra adb_nice "0")"
		procd_set_param stdout 1
		procd_set_param stderr 1
		procd_close_instance
	fi
}

reload_service()
{
	rc_procd start_service reload
}

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

restart()
{
	rc_procd start_service restart
}

suspend()
{
	rc_procd start_service suspend
}

resume()
{
	rc_procd start_service resume
}

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

report()
{
	rc_procd "${adb_script}" report "${1:-"+"}" "${2:-"50"}" "${3:-"false"}" "${4:-"true"}"
}

status_service()
{
	local key keylist value
	local rtfile="$(uci_get adblock extra adb_rtfile "/tmp/adb_runtime.json")"

	if [ -s "${rtfile}" ]
	then
		printf "%s\\n" "::: adblock runtime information"
		json_load_file "${rtfile}"
		json_select data
		json_get_keys keylist
		for key in ${keylist}
		do
			json_get_var value "${key}"
			printf "  + %-15s : %s\\n" "${key}" "${value}"
		done
	else
		printf "%s\\n" "::: no adblock runtime information available"
	fi
}

service_triggers()
{
	local trigger trigger_list="$(uci_get adblock global adb_trigger)"
	local delay="$(uci_get adblock extra adb_triggerdelay "2")"
	local type="$(uci_get adblock extra adb_starttype "start")"

	PROCD_RELOAD_DELAY=$((delay*1000))
	
	if [ -z "${trigger_list}" ] && [ -r "/lib/functions/network.sh" ]
	then
		. "/lib/functions/network.sh"
		network_find_wan trigger_list
	fi

	if [ -n "${trigger_list}" ]
	then
		for trigger in ${trigger_list}
		do
			if [ "${trigger}" != "none" ] && [ "${trigger}" != "timed" ]
			then
				procd_add_interface_trigger "interface.*.up" "${trigger}" "${adb_init}" "${type}"
			fi
		done
	else
		procd_add_raw_trigger "interface.*.up" ${PROCD_RELOAD_DELAY} "${adb_init}" "${type}"
	fi
	procd_add_reload_trigger "adblock"
}
