#!/bin/sh

uci -q batch <<-EOF >/dev/null 2>&1
	delete ucitrack.@tailscale[-1]
	commit ucitrack
EOF

# Enable the init.d service so that:
#   1) it runs on boot — registering the uci reload trigger with procd,
#      without which LuCI's "Enable" checkbox would be a no-op;
#   2) start_instance still returns early when enabled=0, so this does NOT
#      start tailscaled against the user's wishes.
# Migrate the old accept_dns flag onto dns_mode. Only touch configs that do
# not have dns_mode yet, so a deliberate choice is never overwritten.
if [ -z "$(uci -q get tailscale.settings.dns_mode)" ]; then
	if [ "$(uci -q get tailscale.settings.accept_dns)" = "1" ]; then
		uci -q set tailscale.settings.dns_mode='magicdns'
	else
		uci -q set tailscale.settings.dns_mode='disabled'
	fi
	uci -q delete tailscale.settings.accept_dns
	uci -q commit tailscale
fi

[ -x /etc/init.d/tailscale ] && {
	/etc/init.d/tailscale enable
	# Start once so service_triggers() fires now, not only after a reboot.
	/etc/init.d/tailscale start >/dev/null 2>&1
}

rm -f /tmp/luci-indexcache*
exit 0
