#!/bin/sh /etc/rc.common
# Copyright (C) 2026 OpenWrt.org
# Open-Box Core Service (sing-box transparent proxy)

START=96
STOP=09
USE_PROCD=1

INSTALL_ROOT="/opt/open-box"

openbox_cleanup() {
	if command -v uci >/dev/null 2>&1; then
		local changed=0
		for rule in openbox_dns openbox_tun_forward openbox_tun_input openbox_v6block; do
			if [ -n "$(uci -q get firewall.$rule 2>/dev/null)" ]; then
				uci -q delete firewall.$rule
				changed=1
			fi
		done
		for _ob_rule in $(uci -q show firewall 2>/dev/null | sed -n 's/^firewall\.\(openbox_srv_[A-Za-z0-9_]*\)=rule$/\1/p'); do
			uci -q delete "firewall.$_ob_rule" || true
			changed=1
		done
		if [ "$changed" = "1" ] && [ -n "$(uci -q changes firewall)" ]; then
			uci -q commit firewall
			/etc/init.d/firewall reload >/dev/null 2>&1 || true
		fi
	fi

	if command -v nft >/dev/null 2>&1; then
		nft delete table inet openbox 2>/dev/null || true
	fi
}

start_service() {
	if [ -f "$INSTALL_ROOT/openwrt/initd/openbox" ] && [ ! -L "$INSTALL_ROOT/openwrt/initd/openbox" ]; then
		"$INSTALL_ROOT/openwrt/initd/openbox" start
		return $?
	fi

	if [ ! -d "$INSTALL_ROOT" ]; then
		echo "[openbox] 核心组件尚未安装在 $INSTALL_ROOT，请先安装或下载核心组件。" >&2
		return 1
	fi

	local deploy_cli="$INSTALL_ROOT/panel/server/cli/deploy.mjs"
	local node_bin="$INSTALL_ROOT/node/bin/node"
	local core_bin="$INSTALL_ROOT/bin/sing-box"

	if [ -x "$node_bin" ] && [ -f "$deploy_cli" ]; then
		OPENBOX_ROOT="$INSTALL_ROOT" ZASHBOARD_DB_PATH="$INSTALL_ROOT/data/openbox.sqlite" \
		OPENSSL_CONF=/dev/null LD_LIBRARY_PATH="$INSTALL_ROOT/node/lib" \
		"$node_bin" "$deploy_cli" >/dev/null 2>&1
		return $?
	elif [ -x "$core_bin" ] && [ -f "$INSTALL_ROOT/etc/config.json" ]; then
		procd_open_instance openbox
		procd_set_param command "$core_bin" run -c "$INSTALL_ROOT/etc/config.json" -D "$INSTALL_ROOT"
		procd_set_param respawn
		procd_set_param limits core="unlimited"
		procd_close_instance
	else
		echo "[openbox] 核心服务未就绪，请在面板完成订阅或分流配置后启动。" >&2
		return 1
	fi
}

stop_service() {
	if [ -f "$INSTALL_ROOT/openwrt/initd/openbox" ] && [ ! -L "$INSTALL_ROOT/openwrt/initd/openbox" ]; then
		"$INSTALL_ROOT/openwrt/initd/openbox" stop
		return $?
	fi

	if [ -x "$INSTALL_ROOT/bin/sing-box" ]; then
		killall -9 sing-box 2>/dev/null || true
	fi
	openbox_cleanup
}

restart() {
	stop
	sleep 1
	start
}

status() {
	if [ -x "$INSTALL_ROOT/bin/sing-box" ] && pidof sing-box >/dev/null; then
		echo "openbox is running (pid $(pidof sing-box))"
		return 0
	fi
	echo "openbox is not running"
	return 1
}
