#!/bin/sh
[ -n "${IPKG_INSTROOT:-}" ] && exit 0
if pidof changeguard_bin >/dev/null 2>&1; then
	printf '%s\n' 'ChangeGuard stopped for upgrade; any active protection has failed.' >&2
fi
# procd knows the PID even when an old release runs a retained tool-<digest>.
old_pids="$(ubus call service list '{"name":"changeguard"}' 2>/dev/null | jsonfilter -e '@.changeguard.instances.*.pid' 2>/dev/null)" || old_pids=""
ubus call service delete '{"name":"changeguard"}' >/dev/null 2>&1 || true
killall changeguard_bin >/dev/null 2>&1 || true
# Wait for the old process to release its runtime lock before postinst.
for attempt in 1 2 3 4 5 6 7 8 9 10; do
	busy=0
	for pid in $old_pids; do
		case "$pid" in ''|*[!0-9]*) continue ;; esac
		kill -0 "$pid" 2>/dev/null && busy=1
	done
	pidof changeguard_bin >/dev/null 2>&1 && busy=1
	[ "$busy" = 1 ] || break
	sleep 1
done
exit 0
