#!/bin/sh /etc/rc.common
#
# Copyright (C) 2025-2026 sirpdboy herboy2008@gmail.com https://github.com/sirpdboy/luci-app-watchdog
# 

START=99
STOP=10
USE_PROCD=1
config=watchdog
dir="/tmp/$config/"

start_service() {
    clear_rule
    procd_open_instance
    enable_value=$(uci get $config.config.enable 2>/dev/null || echo "0")
    [ "$enable_value" -ne "0" ] && procd_set_param command /usr/share/$config/$config && echo "$config is starting now ..."
    procd_close_instance
}

reload_service() {
    stop
    sleep 1
    start
}

detect_firewall_type() {
    if command -v nft >/dev/null && [ -x /sbin/fw4 ]; then
        echo "nft"
    elif command -v iptables >/dev/null || command -v ip6tables >/dev/null; then
        echo "iptables"
    else
        echo "unknown"
    fi
}
clear_rule(){


    local fw_type=$(detect_firewall_type)

    if [ "$fw_type" = "nft" ]; then

        local drop_handles=$(nft -a list ruleset 2>/dev/null | grep -E "watchdog Drop rule" | awk '{print $NF}')
        for handle in $drop_handles; do
            nft delete rule inet fw4 input handle $handle 2>/dev/null
        done
        nft delete rule inet fw4 watchdog_input ip saddr @watchdog_blacklist 2>/dev/null
        nft delete rule inet fw4 watchdog_input ip6 saddr @watchdog_blacklistv6 2>/dev/null
        nft delete rule inet fw4 watchdog_input ether saddr @watchdog_blacklistbridge 2>/dev/null
        nft delete chain inet fw4 watchdog_input 2>/dev/null
        nft delete set inet fw4 watchdog_blacklist 2>/dev/null
        nft delete set inet fw4 watchdog_blacklistv6 2>/dev/null
        nft delete set inet fw4 watchdog_blacklistbridge 2>/dev/null
    elif [ "$fw_type" = "iptables" ]; then
        iptables -D INPUT -m set --match-set watchdog_blacklist src -j DROP 2>/dev/null
        iptables -D INPUT -m set --match-set watchdog_range src -j DROP 2>/dev/null
        ip6tables -D INPUT -m set --match-set watchdog_blacklistv6 src -j DROP 2>/dev/null
        ipset destroy watchdog_blacklist 2>/dev/null
        ipset destroy watchdog_blacklistv6 2>/dev/null
        ipset destroy watchdog_range 2>/dev/null
    fi

}
stop_service() {
    [ -f ${dir}child_pid ] && parent_pid=$(cat ${dir}child_pid)
    clear_rule
    [ -n "$parent_pid" ] && {
        child_pids=$(pgrep -P $parent_pid)
        echo "Terminating child processes of $config..."
        for child_pid in $child_pids; do
            kill $child_pid
        done
    }
    local pids=$(ps | grep "$config" | grep -v grep | grep -v $$ | awk '{print $1}')
	[ -n "$pids" ] && echo "$pids" | xargs kill 2>/dev/null
    echo "Terminating $config process..."
}

service_triggers() {
    procd_add_reload_trigger $config
}
