#!/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 AND /etc/xray/run.json exists.
#     On a fresh/misconfigured box start_service exits cleanly with no instance
#     and no data-plane changes, so boot connectivity is NEVER affected.
#   * 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
UCI_CONF=/etc/config/shater
RUN_DIR=/var/run/xray
PID_FILE=/var/run/xray/xray.pid
ASSET_DIR=/usr/share/xray

# --- 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.
shater_to_dec() {
	case "$1" in
		0x*|0X*|[0-9]*) echo $(( $1 )) ;;
		*) return 1 ;;
	esac
}

# 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.
	local tbase base t
	tbase=$(uci -q get shater.globals.table_base)
	[ -n "$tbase" ] || tbase="0x2000"
	base=$(shater_to_dec "$tbase") || return 0
	[ -n "$base" ] || return 0

	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.
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 enabled and a generated runtime config exists.
	# Returning with no instance opened means procd supervises nothing — the
	# box keeps forwarding traffic exactly as if this package were absent.
	shater_enabled || return 0
	[ -f "$RUN_JSON" ] || return 0

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

	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(10) timeout(2) retries(5): a low threshold means an engine that ran
	# >10s and is then restarted (xrayctl reloadXray SIGTERMs it to pick up a fresh
	# run.json without a reconcile) is respawned unconditionally — only genuine
	# <10s crash loops count toward the retry limit and eventually give up.
	procd_set_param respawn 10 2 5
	procd_set_param file "$RUN_JSON"                        # restart if run.json changes
	procd_set_param file "$UCI_CONF"                        # restart if UCI changes
	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

	# Persist policy routing / nft table for the freshly (re)started engine.
	shater_reconcile
}

service_started() {
	# Re-arm reconcile once procd reports the instance up (covers the case where
	# reconcile in start_service raced the listener).
	shater_enabled && shater_reconcile
	return 0
}

stop_service() {
	# procd stops the xray instance itself; we only tear down our kernel state.
	shater_teardown
}

reload_service() {
	# Fired by the `shater` config.change reload-trigger. `start` re-runs
	# start_service, which regenerates run.json + reconciles nft/routing (a single
	# `xrayctl reconcile`); procd's file-watch then restarts xray if run.json
	# changed. 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 (a second, needless `xray -test`), 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"
}
