#!/bin/sh
if [ -f /opt/clash/.config.yaml.upgrade.bak ]; then
	mv /opt/clash/.config.yaml.upgrade.bak /opt/clash/config.yaml
	FIRST_INSTALL=0
else
	FIRST_INSTALL=1
fi
[ -n "$IPKG_INSTROOT" ] || {
	/etc/init.d/rpcd reload
	rm -f /tmp/luci-*

	# On first install the default config.yaml is just a usable example
	# (no real proxies configured). Prevent auto-start on next boot so the
	# user can edit /opt/clash/config.yaml first. "Start Service" in LuCI
	# re-enables it via `/etc/init.d/clash enable`.
	if [ "$FIRST_INSTALL" = "1" ]; then
		/etc/init.d/clash disable 2>/dev/null || true
	fi

	# Ensure periodic clash-rules update cron job exists
	CRON_FILE="/etc/crontabs/root"
	CRON_LINE="*/30 * * * * /opt/clash/bin/clash-rules update >/dev/null 2>&1"

	[ -f "$CRON_FILE" ] || touch "$CRON_FILE"
	if ! grep -Fq "/opt/clash/bin/clash-rules update" "$CRON_FILE" 2>/dev/null; then
		echo "$CRON_LINE" >> "$CRON_FILE"
		/etc/init.d/cron restart >/dev/null 2>&1 || true
	fi
}
exit 0
