#!/bin/sh
# Copyright 2023-2026 MOSSDeF, Stan Grishin (stangri@melmac.ca)
# shellcheck disable=SC2015,SC3043

readonly pkg='adblock-fast'

# Source the init script for $initCompat (compat-era stamp) and $_ucode.
readonly initFile="/etc/init.d/${pkg}"
# shellcheck disable=SC1091
[ -s "$initFile" ] && . "$initFile"

# Capture the previously-stamped config_compat before we (re)stamp it at
# the end of this script — used to gate one-shot migrations.
old_compat="$(uci -q get "${pkg}.config.config_compat")"

# ── Transition to list names ─────────────────────────────────────────
# Adds 'name' to file_url sections that lack one, using the pristine default config

# Find pristine default: apk uses .apk-new, opkg uses -opkg
pristine=''
for f in "/etc/config/${pkg}.apk-new" "/etc/config/${pkg}-opkg"; do
	[ -s "$f" ] && pristine="$f" && break
done

_find_name() { grep -B1 "$1" "$pristine" 2>/dev/null | head -1 | cut -d "'" -f2; }

if [ -n "$pristine" ]; then
	# shellcheck disable=SC1091
	. /lib/functions.sh
	add_name() {
		local cfg="$1" url name label
		config_get url "$cfg" 'url'
		config_get name "$cfg" 'name'
		if [ -z "$name" ]; then
			label="${url##*//}"; label="${label%%/*}"
			name="$(_find_name "$url")"
			if [ -n "$name" ]; then
				uci set "${pkg}.${cfg}.name=${name}"
				printf "  %s: %s\n" "$label" "$name" >&2
			fi
		fi
	}
	config_load "$pkg"
	config_foreach add_name 'file_url'
fi

# ── Migrate to 1.2.0 ────────────────────────────────────────────────

oldval="$(uci -q get "${pkg}.config.debug")"
if [ -n "$oldval" ]; then
	uci set "${pkg}.config.debug_init_script=${oldval}"
	uci -q delete "${pkg}.config.debug"
fi

oldval="$(uci -q get "${pkg}.config.proc_debug")"
if [ -n "$oldval" ]; then
	uci set "${pkg}.config.debug_performance=${oldval}"
	uci -q delete "${pkg}.config.proc_debug"
fi

# ── Migrate sanity_check → dnsmasq_sanity_check ─────────────────────

if [ -z "$(uci -q get "${pkg}.config.dnsmasq_sanity_check")" ] \
	&& [ -n "$(uci -q get "${pkg}.config.sanity_check")" ]; then
	oldval="$(uci -q get "${pkg}.config.sanity_check")"
	uci set "${pkg}.config.dnsmasq_sanity_check=${oldval}"
	uci -q delete "${pkg}.config.sanity_check"
fi

# ── Migrate parallel_downloads bool → numeric cap (one-shot) ─────────
# Pre-1.2.4 (compat < 15) treated parallel_downloads as a bool — '1' meant
# "parallel on". 1.2.4 made it a numeric cap. Convert the legacy '1' to 8.
# Once a 1.2.4+ run stamps config_compat below, this never re-fires.

if [ "${old_compat:-14}" -lt 15 ] 2>/dev/null; then
	[ "$(uci -q get "${pkg}.config.parallel_downloads")" = "1" ] && \
		uci set "${pkg}.config.parallel_downloads=8"
fi

# ── Version tracking  ──────────────────────────
[ -n "$initCompat" ] && uci set "${pkg}.config.config_compat=$initCompat"
uci set "${pkg}.config.config_version=$($_ucode version 2>/dev/null)"

[ -n "$(uci -q changes "$pkg" 2>/dev/null)" ] && uci commit "$pkg"

exit 0
