#!/bin/sh

_root="${IPKG_INSTROOT:-}"
_map_source="$_root/usr/share/auto-ipoe/proto/map.sh"
_map_live="$_root/lib/netifd/proto/map.sh"
_map_backup="${_map_live}.old"
_map_backup_tmp="${_map_backup}.tmp.$$"
_map_live_tmp="${_map_live}.tmp.$$"
_time_sync="$_root/usr/libexec/auto-ipoe-time-sync"
_cbt_service="$_root/etc/init.d/auto-ipoe-cbt-monitor"
_cbt_manager="$_root/usr/libexec/auto-ipoe-cbt-monitor"

cleanup_map_temps() {
	rm -f "$_map_backup_tmp" "$_map_live_tmp"
}
trap cleanup_map_temps EXIT
trap 'exit 1' HUP INT TERM

[ -f "$_map_source" ] && [ ! -L "$_map_source" ] || {
	echo "error: packaged Auto-IPoE MAP protocol is unavailable" >&2
	exit 1
}
[ -f "$_map_live" ] && [ ! -L "$_map_live" ] || {
	echo "error: platform MAP protocol is unavailable or unsafe" >&2
	exit 1
}

if [ -z "$IPKG_INSTROOT" ]; then
	[ -x "$_time_sync" ] || {
		echo "error: Auto-IPoE time synchronization helper is unavailable" >&2
		exit 1
	}
	[ -x "$_cbt_service" ] && [ -x "$_cbt_manager" ] || {
		echo "error: Auto-IPoE connectivity monitor service is unavailable" >&2
		exit 1
	}
	"$_time_sync" || exit 1
fi

if [ -e "$_map_backup" ] || [ -L "$_map_backup" ]; then
	echo "error: Auto-IPoE IPK replacement is unsupported; platform MAP backup already exists" >&2
	exit 1
fi

mkdir -p "$(dirname "$_map_live")"
if ! cp -p "$_map_live" "$_map_backup_tmp" ||
   ! mv -f "$_map_backup_tmp" "$_map_backup"; then
	echo "error: could not preserve the platform MAP protocol" >&2
	exit 1
fi

if ! cp "$_map_source" "$_map_live_tmp" ||
   ! chmod 0755 "$_map_live_tmp" ||
   ! mv -f "$_map_live_tmp" "$_map_live"; then
	echo "error: could not install the Auto-IPoE MAP protocol" >&2
	exit 1
fi

# Refresh LuCI's generated module cache without enabling or provisioning an
# Internet mode. The user remains responsible for selecting Auto-IPoE.
if [ -z "$IPKG_INSTROOT" ]; then
	rm -rf /tmp/luci-* 2>/dev/null || true
	if ! "$_cbt_service" enable >/dev/null 2>&1 ||
	   ! "$_cbt_service" start; then
		"$_cbt_service" disable >/dev/null 2>&1 || true
		"$_cbt_manager" restore >/dev/null 2>&1 || true
		if ! mv -f "$_map_backup" "$_map_live"; then
			echo "error: connectivity monitor failed and the platform MAP protocol could not be restored" >&2
			exit 1
		fi
		echo "error: Auto-IPoE connectivity monitor could not be activated" >&2
		exit 1
	fi
fi

exit 0
