#!/bin/sh /etc/rc.common
# /etc/init.d/shater — procd supervisor for the Shater data plane.
#
# Runs the stock xray engine (/usr/bin/xray) against xrayctl's generated
# /etc/xray/run.json, and drives xrayctl's idempotent `reconcile` to (re)persist
# policy routing (ip rules/routes in our reserved table base) and our nft table.
#
# RELIABILITY CONTRACT (the "железно" layer):
#   * Completely INERT unless globals.enabled=1. On a fresh/misconfigured box
#     start_service exits cleanly with no instance and no data-plane changes,
#     so boot connectivity is NEVER affected.
#   * The interception data plane may only exist while this service is meant to
#     be running. `start` raises ACTIVE_FLAG, `stop` clears it AND tears the
#     data plane down; hotplug/cron reconcile ONLY while the flag is up, so an
#     admin `stop` STICKS — no background actor may resurrect interception.
#   * The engine must never be permanently abandoned while interception stands:
#     respawn retries are infinite (procd never gives up); a sustained-dead
#     engine is additionally escalated by the shater-cron watchdog.
#   * Teardown only ever touches OUR resources: nft table `inet shater` and the
#     routing tables in the reserved base (default 0x2000). fw4's table and the
#     management/LAN paths are never touched.
#   * busybox ash only — no bashisms.

USE_PROCD=1
START=99          # after network + firewall + dnsmasq
STOP=10

PROG=/usr/bin/xray
XRAYCTL=/usr/bin/xrayctl
RUN_JSON=/etc/xray/run.json
RUN_DIR=/var/run/xray
PID_FILE=/var/run/xray/xray.pid
ASSET_DIR=/usr/share/xray
# Raised while the service is meant to be running; the ONLY token that lets
# hotplug/shater-cron touch the data plane. tmpfs => cleared by reboot, so
# nothing reconciles before this init has run at boot.
ACTIVE_FLAG=/var/run/shater.active

# --- helpers ---------------------------------------------------------------

# True only when the stack is explicitly enabled in UCI.
shater_enabled() {
	local en
	en=$(uci -q get shater.globals.enabled) || return 1
	[ "$en" = "1" ]
}

# Normalize a UCI numeric option (hex "0x2000" or decimal "8192") to decimal.
# Rejects anything that is not a clean hex/decimal literal — a malformed value
# must NOT silently disable teardown (the caller falls back to the default).
shater_to_dec() {
	local v="$1" rest
	case "$v" in
		0x*|0X*)
			rest="${v#0[xX]}"
			[ -n "$rest" ] || return 1
			case "$rest" in *[!0-9a-fA-F]*) return 1 ;; esac
			;;
		*)
			[ -n "$v" ] || return 1
			case "$v" in *[!0-9]*) return 1 ;; esac
			;;
	esac
	echo $(( v ))
}

# Best-effort removal of OUR data-plane state. Safe to run repeatedly and when
# nothing is set up. Restores plain routing/forwarding immediately.
shater_teardown() {
	# Interception table (owned by us; generated by xrayctl at apply time).
	if command -v nft >/dev/null 2>&1; then
		nft delete table inet shater 2>/dev/null
	fi

	# Policy routing in our reserved table block. We only clear tables at/above
	# table_base, never the main/default/local tables or fw4 state. A malformed
	# table_base falls back to the shipped default — teardown must ALWAYS run.
	local tbase base t
	tbase=$(uci -q get shater.globals.table_base)
	[ -n "$tbase" ] || tbase="0x2000"
	base=$(shater_to_dec "$tbase") || base=8192

	t="$base"
	while [ "$t" -lt $(( base + 64 )) ]; do
		# Delete every ip rule that points at this table (there may be more
		# than one), for both address families, then flush the table.
		while ip rule del table "$t" 2>/dev/null; do :; done
		while ip -6 rule del table "$t" 2>/dev/null; do :; done
		ip route flush table "$t" 2>/dev/null
		ip -6 route flush table "$t" 2>/dev/null
		t=$(( t + 1 ))
	done
}

# Idempotent kernel reconcile via the control-plane (routing + nft). Brings the
# UCI schema forward first (idempotent; refuses a newer schema) so an upgraded
# xrayctl never generates from a stale config. xrayctl serializes itself with
# an flock and hash-compares run.json, so re-running this is safe and cheap.
shater_reconcile() {
	[ -x "$XRAYCTL" ] && "$XRAYCTL" migrate >/dev/null 2>&1
	[ -x "$XRAYCTL" ] && "$XRAYCTL" reconcile >/dev/null 2>&1
	return 0
}

# --- procd lifecycle -------------------------------------------------------

start_service() {
	# Guard: stay inert unless explicitly enabled.
	shater_enabled || return 0

	# Guard: never install interception without a working engine binary. A
	# half-removed/failed xray upgrade must degrade to "plugin off", not to a
	# LAN whose traffic is diverted into nothing.
	if [ ! -x "$PROG" ]; then
		logger -t shater -p daemon.err \
			"xray binary missing/not executable at $PROG — refusing to start (LAN stays on plain routing)"
		return 0
	fi

	mkdir -p "$RUN_DIR" "$(dirname "$RUN_JSON")"

	# run.json is generated state (lost on sysupgrade). If it is missing but the
	# stack is enabled, regenerate it from UCI before opening the instance —
	# otherwise the box comes up enabled-but-engineless and the first background
	# reconcile would install interception with nothing listening behind it.
	if [ ! -f "$RUN_JSON" ]; then
		[ -x "$XRAYCTL" ] && "$XRAYCTL" migrate >/dev/null 2>&1
		[ -x "$XRAYCTL" ] && "$XRAYCTL" reconcile >/dev/null 2>&1
		if [ ! -f "$RUN_JSON" ]; then
			logger -t shater -p daemon.err \
				"enabled but could not generate $RUN_JSON — staying inert (check 'xrayctl reconcile' output)"
			return 0
		fi
	fi

	procd_open_instance shater
	# xray runs in the FOREGROUND under procd (must never daemonize).
	procd_set_param command "$PROG" run -c "$RUN_JSON"
	procd_set_param env XRAY_LOCATION_ASSET="$ASSET_DIR"   # geoip.dat/geosite.dat
	# threshold(3600) timeout(5) retries(0=INFINITE): procd must NEVER give up on
	# the engine while our interception rules stand — an abandoned engine with
	# live TPROXY+DNS-hijack rules is a permanent LAN blackout. A genuine crash
	# loop retries every 5s (cheap); sustained death is escalated by the
	# shater-cron watchdog (which fails open / alerts per kill_switch policy).
	procd_set_param respawn 3600 5 0
	# NOTE: deliberately NO `procd_set_param file` watches. run.json changes are
	# propagated by xrayctl itself (hash-compare + engine SIGTERM on real change),
	# and UCI edits flow through the reload trigger below. A file-watch here
	# would bounce the tunnel (dropping every proxied connection) on every UCI
	# commit even when the rendered config is byte-identical.
	procd_set_param stdout 1                                # -> logread
	procd_set_param stderr 1
	procd_set_param term_timeout 10
	procd_set_param pidfile "$PID_FILE"
	procd_close_instance

	# Mark the stack live for hotplug/cron, then persist policy routing / nft
	# for the freshly (re)started engine.
	mkdir -p "$(dirname "$ACTIVE_FLAG")"
	: > "$ACTIVE_FLAG"
	shater_reconcile
}

stop_service() {
	# Drop the live-flag FIRST so a concurrent hotplug/cron tick cannot rebuild
	# what we are about to tear down; procd stops the xray instance itself.
	rm -f "$ACTIVE_FLAG"
	shater_teardown
}

reload_service() {
	# Fired by the `shater` config.change reload-trigger. `start` re-runs
	# start_service, which reconciles nft/routing; xrayctl's reconcile compares
	# the rendered run.json hash and restarts the engine ONLY on real change.
	# When the stack is disabled we tear our resources down. We must NOT call
	# `shater_reconcile` in addition to `start` — that would run reconcile twice
	# per reload, and any path that makes `xrayctl reconcile` itself invoke
	# `/etc/init.d/shater reload` would turn this into an unbounded fork storm.
	if shater_enabled; then
		start
	else
		stop
	fi
}

service_triggers() {
	procd_add_reload_trigger "shater"
}
