#!/bin/sh

[ -f /usr/share/honk/download_dashboard.sh ] && chmod +x /usr/share/honk/download_dashboard.sh
[ -f /usr/share/honk/download_zashboard.sh ] && rm -f /usr/share/honk/download_zashboard.sh

mkdir -p /etc/honk/config.d /etc/honk/state
[ -f /etc/honk/config.d/api.dae ] || touch /etc/honk/config.d/api.dae
dash=$(uci -q get honk.config.dashboard || uci -q get honk.@honk[0].dashboard || echo "")
if [ "$dash" = "none" ]; then
	: > /etc/honk/config.d/api.dae
fi

# Migrate legacy /etc/honk/dashboard directory
if [ -d /etc/honk/dashboard ] && [ ! -d /etc/honk/doona ]; then
	mv /etc/honk/dashboard /etc/honk/doona
elif [ -d /etc/honk/dashboard ] && [ -d /etc/honk/doona ]; then
	rm -rf /etc/honk/dashboard
fi
if [ -f /etc/honk/config.d/api.dae ]; then
	sed -i "s|/etc/honk/dashboard|/etc/honk/doona|g" /etc/honk/config.d/api.dae 2>/dev/null || true
fi
chmod -R u=rwX,go= /etc/honk 2>/dev/null || true
chmod 700 /etc/honk /etc/honk/config.d /etc/honk/state 2>/dev/null || true


# Clean legacy clash_api configuration from config.dae
if [ -f /etc/honk/config.dae ]; then
	ucode -e '
	import { readfile, writefile } from "fs";
	let c = readfile("/etc/honk/config.dae");
	if (c) {
		let lines = split(c, "\n");
		let out = [];
		let skip = 0;
		for (let line in lines) {
			let trim = replace(line, /^[ \t]+|[ \t]+$/, "");
			if (!skip && match(trim, /^[#\/]*\s*clash_api\s*\{/)) {
				skip = 1;
				continue;
			}
			if (skip) {
				if (match(trim, /\{/)) skip++;
				if (match(trim, /\}/)) skip--;
				continue;
			}
			push(out, line);
		}
		let res = join("\n", out);
		res = replace(res, /[ \t]*experimental\s*\{\s*\}[ \t]*\n?/, "");
		if (res != c) writefile("/etc/honk/config.dae", res);
	}
	' 2>/dev/null || true
fi

rm -rf /tmp/luci-*
/etc/init.d/rpcd reload 2>/dev/null

exit 0

