#!/bin/sh /etc/rc.common
# /etc/init.d/shater-cron — periodic auto-updater for subscriptions & rulesets.
#
# A tiny procd-supervised loop that, once per tick, checks every enabled
# subscription and url-ruleset against its per-item `update_interval` and runs
#   xrayctl sub update <name>       (subscriptions)
#   xrayctl ruleset update <name>   (url rulesets)
# when the item is due, then a single `xrayctl reconcile` if anything changed.
#
# RELIABILITY CONTRACT (same "железно" posture as /etc/init.d/shater):
#   * Fully INERT unless globals.enabled=1 and xrayctl is present. On a fresh or
#     disabled box no instance is opened and nothing ever runs.
#   * Only ever invokes xrayctl verbs — never touches the data plane directly.
#   * Due-ness is tracked with epoch stamp FILES under a tmpfs run dir, so no
#     dependence on `date -r`. Stamps are lost on reboot => every item is due at
#     boot, giving a fetch-at-boot exactly as the feature catalog requires.
#   * busybox ash only — no bashisms. `sh -n` clean.

USE_PROCD=1
START=96          # after the main shater init (99) is irrelevant; loop self-guards
STOP=11

# `loop` is an internal action procd re-execs to run the periodic body.
EXTRA_COMMANDS="loop"
EXTRA_HELP="	loop	internal: run the periodic update loop (invoked by procd)"

INIT_SCRIPT=/etc/init.d/shater-cron
XRAYCTL=/usr/bin/xrayctl
STAMP_DIR=/var/run/shater/cron
TICK=60                          # seconds between due-checks
DEFAULT_SUB_INTERVAL=6h
DEFAULT_RS_INTERVAL=24h

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

shater_enabled() {
	local en
	en=$(uci -q get shater.globals.enabled) || return 1
	[ "$en" = "1" ]
}

# Convert 30m|6h|24h|2d|3600 -> seconds on stdout. $2 is a fallback token used
# when the input is empty or malformed.
shater_ivl_secs() {
	local v="$1" def="$2" n u
	[ -n "$v" ] || v="$def"
	n=$(echo "$v" | sed 's/[^0-9].*$//')
	u=$(echo "$v" | sed 's/^[0-9]*//')
	[ -n "$n" ] || { echo 21600; return; }
	case "$u" in
		s|"") echo "$n" ;;
		m|M)  echo $(( n * 60 )) ;;
		h|H)  echo $(( n * 3600 )) ;;
		d|D)  echo $(( n * 86400 )) ;;
		*)    echo $(( n )) ;;
	esac
}

# Due if now - stamp >= interval. $1 stamp file, $2 interval seconds.
shater_due() {
	local stamp="$1" ivl="$2" now last
	now=$(date +%s)
	last=$(cat "$stamp" 2>/dev/null)
	[ -n "$last" ] || last=0
	[ $(( now - last )) -ge "$ivl" ]
}

shater_stamp() { mkdir -p "$STAMP_DIR"; date +%s > "$1"; }

# Walk anonymous `config subscription` / `config ruleset` sections by index and
# run any that are due. Echoes non-empty on stdout if at least one item updated.
shater_run_due() {
	local i name en ivl secs stamp changed=""

	# Subscriptions.
	i=0
	while uci -q get "shater.@subscription[$i]" >/dev/null 2>&1; do
		name=$(uci -q get "shater.@subscription[$i].name")
		en=$(uci -q get "shater.@subscription[$i].enabled")
		[ -z "$en" ] && en=1
		if [ -n "$name" ] && [ "$en" = "1" ]; then
			ivl=$(uci -q get "shater.@subscription[$i].update_interval")
			secs=$(shater_ivl_secs "$ivl" "$DEFAULT_SUB_INTERVAL")
			stamp="$STAMP_DIR/sub.$name"
			if shater_due "$stamp" "$secs"; then
				"$XRAYCTL" sub update "$name" >/dev/null 2>&1
				shater_stamp "$stamp"
				changed=1
			fi
		fi
		i=$(( i + 1 ))
	done

	# Rulesets (only url sources auto-update; others have nothing to fetch).
	i=0
	while uci -q get "shater.@ruleset[$i]" >/dev/null 2>&1; do
		name=$(uci -q get "shater.@ruleset[$i].name")
		src=$(uci -q get "shater.@ruleset[$i].source")
		if [ -n "$name" ] && [ "$src" = "url" ]; then
			ivl=$(uci -q get "shater.@ruleset[$i].update_interval")
			secs=$(shater_ivl_secs "$ivl" "$DEFAULT_RS_INTERVAL")
			stamp="$STAMP_DIR/rs.$name"
			if shater_due "$stamp" "$secs"; then
				"$XRAYCTL" ruleset update "$name" >/dev/null 2>&1
				shater_stamp "$stamp"
				changed=1
			fi
		fi
		i=$(( i + 1 ))
	done

	[ -n "$changed" ] && echo 1
}

# loop: the foreground body supervised by procd. Runs due items each tick and
# exits when the stack is disabled so `reload`/`stop` cleanly tears it down.
# Exposed as a custom rc.common action (see EXTRA_COMMANDS) for procd to re-exec.
loop() {
	mkdir -p "$STAMP_DIR"
	while shater_enabled; do
		changed=$(shater_run_due)
		# Schedule boundary: `schedule due` prints "1" only when the set of active
		# time-scheduled rules changed since the last tick, so we reconcile a few
		# times a day at window edges — not every minute.
		sched=$("$XRAYCTL" schedule due 2>/dev/null)
		if [ -n "$changed" ] || [ -n "$sched" ]; then
			"$XRAYCTL" reconcile >/dev/null 2>&1
		fi
		sleep "$TICK"
	done
}

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

start_service() {
	[ -x "$XRAYCTL" ] || return 0
	shater_enabled || return 0

	procd_open_instance shater-cron
	# Re-exec ourselves as the loop body so procd supervises a single process.
	procd_set_param command /bin/sh "$INIT_SCRIPT" loop
	procd_set_param respawn 3600 10 0     # threshold timeout always-retry
	procd_set_param file /etc/config/shater # restart the loop when UCI changes
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance
}

reload_service() {
	# UCI changed: bounce the loop so new intervals/items take effect. If the
	# stack was disabled, the loop self-exits and start re-guards to no-op.
	stop
	start
}

service_triggers() {
	procd_add_reload_trigger "shater"
}
