#!/bin/sh
# /etc/uci-defaults/30_shater-core
#
# One-time, idempotent setup for shater-core. Runs on first boot (and via the
# default postinst on a live opkg/apk install). Must exit 0 so it is cleared and
# not retried. Everything here is safe to run more than once.

RT_TABLES=/etc/iproute2/rt_tables

# Append "<id>  <name>" to rt_tables only if neither the id nor the name is
# already present. Purely cosmetic (readable `ip rule`/`ip route` output);
# xrayctl allocates the rest of the reserved block numerically.
seed_rt_table() {
	local id="$1" name="$2"
	[ -f "$RT_TABLES" ] || return 0
	grep -qE "^[[:space:]]*${id}[[:space:]]" "$RT_TABLES" && return 0
	grep -qE "[[:space:]]${name}[[:space:]]*\$" "$RT_TABLES" && return 0
	printf '%s\t%s\n' "$id" "$name" >> "$RT_TABLES"
}

# Reserved routing-table base 0x2000 == 8192.
seed_rt_table 8192 shater

# Enable the service at boot. The init guard keeps everything inert until
# globals.enabled='1' and /etc/xray/run.json exist, so enabling here can never
# break connectivity on a fresh box.
[ -x /etc/init.d/shater ] && /etc/init.d/shater enable

# Enable the per-item auto-update loop (subscriptions / url rulesets). It is
# equally inert until globals.enabled='1', so enabling on a fresh box is safe.
[ -x /etc/init.d/shater-cron ] && /etc/init.d/shater-cron enable

# Seed the built-in preset packs (disabled) so the LuCI Rules page renders their
# toggles. Idempotent: only creates a section that does not yet exist.
seed_preset() {
	local sid="$1" name="$2" s n
	uci -q get "shater.$sid" >/dev/null 2>&1 && return 0
	# A pack section may already exist under a DIFFERENT section id (created by
	# the LuCI seeding or an older release) — match by pack name, not just id,
	# or we would duplicate the toggle.
	for s in $(uci -q show shater 2>/dev/null | sed -n "s/^shater\.\([^.=]*\)=preset$/\1/p"); do
		n=$(uci -q get "shater.$s.name")
		[ "$n" = "$name" ] && return 0
	done
	uci set "shater.$sid=preset"
	uci set "shater.$sid.name=$name"
	uci set "shater.$sid.enabled=0"
}
if uci -q get shater.globals >/dev/null 2>&1 || [ -f /etc/config/shater ]; then
	seed_preset block_ads block-ads
	seed_preset ru_bypass ru-bypass
	seed_preset private   private
	uci -q commit shater
fi

# Bring the UCI schema forward on upgrade (idempotent; refuses a newer schema).
[ -x /usr/bin/xrayctl ] && /usr/bin/xrayctl migrate >/dev/null 2>&1

# Apply our sysctl knobs NOW (boot applies them via procd's sysctl service, but
# on a live opkg/apk install nothing else re-reads sysctl.d — without this, an
# install→enable→apply flow hits the rp_filter "rules match but nothing works"
# failure until the first reboot). Idempotent; unknown keys are ignored.
[ -f /etc/sysctl.d/99-shater.conf ] && sysctl -p /etc/sysctl.d/99-shater.conf >/dev/null 2>&1

exit 0
