#!/bin/sh /etc/rc.common
# iKuaiWrt: make RUNTIME package installs behave like a normal OpenWrt boot.
#
# OpenWrt applies uci-defaults, reconciles menu dependencies and loads new rpcd
# ACLs only during boot. Our container is long-running, so an app installed from
# LuCI / iStore leaves gaps: missing config, hidden menu (unmet "depends.uci"),
# and an unknown ACL (rpcd caches the list at startup) -- all of which surface as
# "No page is registered at '/admin/services/<app>'". This watcher reacts to any
# package change (opkg status DB) and closes every gap.
START=96
STOP=10
USE_PROCD=1

start_service() {
	procd_open_instance
	procd_set_param command /bin/sh -c '
		last=""
		while :; do
			cur="$(md5sum /usr/lib/opkg/status 2>/dev/null | cut -d" " -f1)"
			if [ -n "$last" ] && [ "$cur" != "$last" ]; then
				for f in /etc/uci-defaults/*; do
					[ -f "$f" ] || continue
					sh "$f" >/dev/null 2>&1
					rm -f "$f"
				done
				[ -x /usr/sbin/ikuai-compat-reconcile-menus ] && /usr/sbin/ikuai-compat-reconcile-menus
				rm -f /tmp/luci-indexcache /tmp/luci-indexcache.*.json /tmp/luci-modulecache
				# rpcd 的会话只在内存里：restart 会把所有 LuCI 登录当场踢掉（"会话过期"）。
				# 只需 SIGHUP reload 重载 ACL —— 实测 reload 后会话仍然有效。绝不要用 restart。
				ubus call rpcd reload >/dev/null 2>&1 || /etc/init.d/rpcd reload >/dev/null 2>&1 || true
			fi
			last="$cur"
			sleep 5
		done'
	procd_set_param respawn 3600 5 5
	procd_set_param stdout 0
	procd_set_param stderr 0
	procd_close_instance
}
