#!/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' \
	    'bundle_path:string' \
	    '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

	config_load parentalcontrol
	config_get_bool enable globals enable 0
	config_get_bool urlfilter globals urlfilter 0

	remove_fw_rules

	if [ "${enable}" -eq "0" ]; then
		# Parental control is disabled
		return 0
	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
				conntrack -F > /dev/null 2>&1
			fi

			# this is for urlfilter daemon
			add_iptables_nfqueue_rules
		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() {
	ret=$(ubus call service list '{"name":"parentalcontrol"}' | jsonfilter -qe '@.parentalcontrol.instances.parentalcontrol.running')
	if [ "$ret" != "true" ]; then
		stop
		start
	else
		configure_fw_rules
		copy_dhcp_leases
		ubus send parentalcontrol.reload
	fi
}

service_triggers() {
	procd_add_reload_trigger "parentalcontrol"
	procd_add_reload_trigger "schedules"
}
