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

# zapret2 init script for OpenWrt
# Delegates to procd-based script in /opt/zapret2

START=99
STOP=10

EXTRA_COMMANDS="status"

# Suppress help output to syslog
help() { :; }

ZAPRET_BASE="/opt/zapret2"
PROCD_SCRIPT="$ZAPRET_BASE/init.d/openwrt/zapret2"
UCI2CONFIG="$ZAPRET_BASE/init.d/openwrt/uci2config"

generate_config() {
    [ -x "$UCI2CONFIG" ] && "$UCI2CONFIG"
}

start() {
    echo "Starting zapret2..."
    generate_config
    "$PROCD_SCRIPT" start >/dev/null 2>&1

    # Fix permissions on log files for LuCI access
    [ -d /tmp/zapret2 ] && chmod 755 /tmp/zapret2
    for f in /tmp/zapret2/*.log; do
        [ -f "$f" ] && chmod 644 "$f"
    done
}

stop() {
    echo "Stopping zapret2..."
    "$PROCD_SCRIPT" stop >/dev/null 2>&1
    # Clean up log files
    for f in /tmp/zapret2/*.log; do
        [ -f "$f" ] && rm -f "$f"
    done
    echo "inactive"
}

reload() {
    # SIGHUP reloads hostlists and ipsets without restart
    # For strategy changes, use restart
    echo "Reloading zapret2 hostlists (SIGHUP)..."
    generate_config
    for pidfile in /var/run/nfqws2_*.pid; do
        [ -f "$pidfile" ] && kill -HUP "$(cat "$pidfile")" 2>/dev/null
    done
}

restart() {
    stop
    sleep 1
    start
}

status() {
    /usr/bin/zapret2 status
}

boot() {
    # Delay on boot to wait for network
    ( sleep 5; start ) &
}
