#!/bin/sh
	# Quiet stop: service may never have been registered with procd (ubus Not found is OK)
	uci -q set wycloud.config.enable=0
	uci -q commit wycloud
	[ -x /etc/init.d/wycloud ] && /etc/init.d/wycloud stop >/dev/null 2>&1 || true
	ubus call service delete '{"name":"wycloud"}' >/dev/null 2>&1 || true

	# --- emergency: restore DNS if still hijacked to dead local resolver ---
	for __s in $(uci -q get dhcp.@dnsmasq[0].server 2>/dev/null); do
		case "$__s" in
			127.0.0.1#*|::1#*) uci -q del_list dhcp.@dnsmasq[0].server="$__s" ;;
		esac
	done
	if [ "$(uci -q get dhcp.@dnsmasq[0].noresolv)" = "1" ] && [ -z "$(uci -q get dhcp.@dnsmasq[0].server 2>/dev/null)" ]; then
		uci -q set dhcp.@dnsmasq[0].noresolv=0
		if [ -s /tmp/resolv.conf.d/resolv.conf.auto ]; then
			uci -q set dhcp.@dnsmasq[0].resolvfile=/tmp/resolv.conf.d/resolv.conf.auto
		elif [ -s /tmp/resolv.conf.auto ]; then
			uci -q set dhcp.@dnsmasq[0].resolvfile=/tmp/resolv.conf.auto
		fi
		uci -q set dhcp.@dnsmasq[0].localuse=1
	fi
	uci -q commit dhcp
	/etc/init.d/dnsmasq restart >/dev/null 2>&1 || true
	# --- emergency: strip leftover nft/iptables jumps for this pkg_tag ---
	if command -v nft >/dev/null 2>&1; then
		for __nft in input forward output dstnat srcnat nat_output mangle_prerouting mangle_output; do
			for __h in $(nft -a list chain inet fw4 $__nft 2>/dev/null | grep -E "wycloud" | awk -F '# handle ' '{print $2}'); do
				nft delete rule inet fw4 $__nft handle $__h >/dev/null 2>&1 || true
			done
		done
		for __h in $(nft -a list chains 2>/dev/null | grep -E "chain wycloud" | awk -F '# handle ' '{print $2}'); do
			nft delete chain inet fw4 handle $__h >/dev/null 2>&1 || true
		done
	fi
	ip rule del fwmark 0x262 table 0x262 >/dev/null 2>&1 || true
	ip route del local 0.0.0.0/0 dev lo table 0x262 >/dev/null 2>&1 || true
	ip -6 rule del fwmark 0x262 table 0x262 >/dev/null 2>&1 || true
	ip -6 route del local ::/0 dev lo table 0x262 >/dev/null 2>&1 || true

	# Preserve config only when upgrading. On uninstall, wipe staging so the next
	# install does not restore old UCI / subscription / cloud cache via uci-defaults.
	if [ "$1" = "upgrade" ]; then
		if [ -f "/etc/config/wycloud" ] && [ ! -f "/tmp/wycloud.bak" ]; then
			cp -f "/etc/config/wycloud" "/tmp/wycloud.bak" >/dev/null 2>&1
			cp -rf "/etc/wycloud" "/tmp/wycloud" >/dev/null 2>&1
			cp -rf "/usr/share/wycloud/ui" "/tmp/wycloud_ui" >/dev/null 2>&1
			cp -rf "/www/luci-static/resources/wycloud/pac" "/tmp/wycloud_pac" >/dev/null 2>&1
		fi
	else
		rm -rf /tmp/wycloud.bak /tmp/wycloud /tmp/wycloud_ui /tmp/wycloud_pac /tmp/wycloud_data >/dev/null 2>&1
	fi
	exit 0
