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

START=95
STOP=10

USE_PROCD=1
PROG=/usr/sbin/urlfilter

. /lib/parentalcontrol/parentalcontrol.sh

validate_global_section() {
	uci_validate_section parentalcontrol globals globals \
	    'enable:bool:1' \
	    'loglevel:uinteger:3' \
	    'queue_num:uinteger:53' \
	    'bundle_path:string' \
	    'default_wan_interface:string:wan' \
	    'urlfilter:bool'
}

remove_fw_rules() {
	# remove urlfilter daemon rules
	remove_iptables_nfqueue_rules
	# remove internet_access and profile_bedtime_schedule rules
	remove_internet_schedule_rules
}

configure_fw_rules() {
	local enable urlfilter queue_num

	config_load parentalcontrol
	config_get_bool enable globals enable 0
	config_get_bool urlfilter globals urlfilter 0
	config_get queue_num globals queue_num 53

	remove_fw_rules

	if [ "${enable}" -eq "0" ]; then
		# Parental control is disabled
		return 0
	fi

	if [ "${queue_num}" -lt 0 ] || [ "${queue_num}" -gt 65535 ]; then
	        log "ERROR: queue_num not in 0-65535"
		return 1
	fi

	if [ "${urlfilter}" -eq "1" ]; then
		if [ ! -f "${OVERRIDE_JSON}" ]; then
			# throw error
	                log "ERROR: urlfiltering disabled at compile time but enabled in config"
		else
			# Now flush the existing connections, otherwise,
			# URL filtering cannot be performed on already open sites.
			if which hw_nat > /dev/null 2>&1; then
				hw_nat -! > /dev/null 2>&1
			fi
			if which conntrack > /dev/null 2>&1; then
				flush_conntrack_for_hosts
			fi

			# this is for urlfilter daemon
			add_iptables_nfqueue_rules "$queue_num"
		fi
	fi

	# this for internet_access and profile_bedtime_schedule sections
	add_internet_schedule_rules
}

copy_dhcp_leases() {
	src="/tmp/dhcp.leases"
	dest="/etc/parentalcontrol/dhcp.leases"
	dest_dir="/etc/parentalcontrol/"

	# Ensure the destination directory exists
	mkdir -p "$dest_dir" || { logger -p err "Failed to create directory $dest_dir."; return 1; }

	# Check if the source file exists and is not empty
	if [ -s "$src" ]; then
		# Compare the content of the source and destination
		if ! cmp -s "$src" "$dest"; then
			# Use atomic copy to prevent partial writes
			tmp_dest="${dest}.tmp"
			cp "$src" "$tmp_dest" && mv "$tmp_dest" "$dest"
		fi
	fi
}

start_service() {
	local enable loglevel bundle_path urlfilter

	config_load parentalcontrol
	validate_global_section

	# add firewall rules
	configure_fw_rules

	if [ "${urlfilter}" -eq "1" ]; then
		# add default bundles
		[ -n "${bundle_path}" ] && mkdir -p ${bundle_path}
		process_default_bundles
		enable_urlfilter_dm
	else
		disable_urlfilter_dm
	fi

	# if the router is, for example, upgraded and then it boots up
	# then /tmp/dhcp.leases will be empty until clients try to get a lease,
	# in that case, hostnames will not be processed by the daemon,
	# for this we copy /tmp/dhcp.leases to /etc/parentalcontrol/dhcp.leases
	# which will be persistent across reboots and upgrade (with keep settings)
	# and will be used as a backup in case /tmp/dhcp.leases is empty
	copy_dhcp_leases

	procd_open_instance "parentalcontrol"
	procd_set_param command nice -n 10 "${PROG}"  # Lower priority
	procd_append_param command -l "${loglevel}"
	procd_set_param respawn
	procd_close_instance
}

stop_service() {
	# remove default bundles
	remove_default_bundles
	remove_fw_rules
	copy_dhcp_leases
}

reload_service() {
	local arg="$1"

	ret=$(ubus call service list '{"name":"parentalcontrol"}' | jsonfilter -qe '@.parentalcontrol.instances.parentalcontrol.running')
	if [ "$ret" != "true" ]; then
		stop
		start
	else
		if [ "$arg" = "network" ]; then
			pidof_sync="$(pidof sync_bundles.sh)"
			[ -n "$pidof_sync" ] && kill "$pidof_sync"
			sleep 5
		fi

		configure_fw_rules
		copy_dhcp_leases
		ubus send parentalcontrol.reload
	fi
}

service_triggers() {
	local enable urlfilter default_wan_interface 

	validate_global_section || {
		return 1
	}

	if [ "${urlfilter}" = "1" ] && [ "$enable" = "1" ] && [ -n "$default_wan_interface" ]; then
		log "Adding interface trigger for $default_wan_interface"
		procd_open_trigger
		procd_add_interface_trigger "interface.*.up" "$default_wan_interface" /etc/init.d/parentalcontrol reload "network"
		procd_close_trigger
	fi

	procd_add_reload_trigger "parentalcontrol"
	procd_add_reload_trigger "schedules"
}
