#!/bin/sh
# Install every IPK shipped inside bmsos-bundle (offline, correct order).
# Idempotent — safe to re-run. LuCI app first so Services menu appears ASAP.
# Writes /tmp/bmsos-install.status so LuCI can show Installing / Done / Failed.

set -e

IPKDIR="/usr/lib/bmsos-bundle/ipks"
MARKER="/etc/bmsos-bundle.ok"
STATUS="/tmp/bmsos-install.status"

log() {
	echo "bmsos-bundle: $*"
	logger -t bmsos-bundle "$*"
}

set_status() {
	# state=installing|done|failed  phase=...  detail=human text
	_state="$1"
	_phase="$2"
	_detail="$3"
	{
		echo "state=${_state}"
		echo "phase=${_phase}"
		echo "detail=${_detail}"
		echo "updated=$(date -u '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null || date)"
	} >"$STATUS"
}

if [ ! -d "$IPKDIR" ]; then
	log "missing $IPKDIR"
	set_status failed missing_ipks "Bundle payload missing on device"
	exit 1
fi

set_status installing wait_opkg_lock "Waiting for Software (opkg) to finish…"

# Wait for outer LuCI opkg to release (LuCI uses /var/lock and/or /tmp/opkg.lock)
i=0
while { [ -e /var/lock/opkg.lock ] || [ -e /tmp/opkg.lock ]; } && [ "$i" -lt 180 ]; do
	i=$((i + 1))
	sleep 1
done
sleep 2

# LuCI app FIRST so Services → bmsOS Gateway + branding land before heavy openssl/openvpn.
ORDER="
luci-app-bmsos-gateway
bmsos-agent
bmsos-vpn
bmsos-gateway
libatomic1
libopenssl3
liblzo2
kmod-tun
openvpn-openssl
"

log "installing offline packages…"

# Count packages present so LuCI can show N/M
PKG_TOTAL=0
for name in $ORDER; do
	f="$(ls -1 "$IPKDIR"/${name}_*.ipk 2>/dev/null | sort -V | tail -n1)"
	[ -n "$f" ] && PKG_TOTAL=$((PKG_TOTAL + 1))
done
[ "$PKG_TOTAL" -gt 0 ] || PKG_TOTAL=1
set_status installing packages "Installing bmsOS packages (0/${PKG_TOTAL})…"

FAILED=""
PKG_N=0
for name in $ORDER; do
	f="$(ls -1 "$IPKDIR"/${name}_*.ipk 2>/dev/null | sort -V | tail -n1)"
	if [ -z "$f" ]; then
		log "skip (not in bundle): $name"
		continue
	fi
	PKG_N=$((PKG_N + 1))
	log "opkg install $(basename "$f")"
	set_status installing "pkg_$name" "Installing ${name} (${PKG_N}/${PKG_TOTAL})…"
	if ! opkg install --force-depends "$f" 2>&1; then
		if ! opkg install --force-reinstall --force-depends "$f" 2>&1; then
			log "WARN failed $f"
			FAILED="$FAILED $name"
		fi
	fi
done

set_status installing defaults "Applying bmsOS defaults…"
if [ -d /etc/uci-defaults ]; then
	for s in /etc/uci-defaults/*bmsos* /etc/uci-defaults/50-bmsos-luci-brand; do
		[ -f "$s" ] || continue
		log "uci-defaults $(basename "$s")"
		( . "$s" ) && rm -f "$s" || true
	done
fi

[ -x /usr/bin/bmsos-luci-brand ] && /usr/bin/bmsos-luci-brand || true
[ -x /etc/init.d/bmsos-modem ] && /etc/init.d/bmsos-modem enable 2>/dev/null || true
[ -x /etc/init.d/bmsos-agent ] && /etc/init.d/bmsos-agent enable 2>/dev/null || true
[ -x /etc/init.d/bmsos-agent-pending ] && /etc/init.d/bmsos-agent-pending enable 2>/dev/null || true

MISSING=""
for need in luci-app-bmsos-gateway bmsos-agent bmsos-vpn bmsos-gateway; do
	if ! opkg list-installed | grep -q "^${need} "; then
		MISSING="$MISSING $need"
	fi
done

# Reload rpcd so ubus plugin + ACL files are live (menu cache bust is client-side in header)
rm -rf /tmp/luci-indexcache /tmp/luci-modulecache 2>/dev/null || true
[ -x /etc/init.d/rpcd ] && /etc/init.d/rpcd restart 2>/dev/null || killall -HUP rpcd 2>/dev/null || true

if [ -n "$MISSING" ]; then
	log "FAILED — missing packages:$MISSING"
	rm -f "$MARKER"
	set_status failed missing "Install failed — missing:$MISSING"
	exit 1
fi

date > "$MARKER"
# Optional: free ~1.7M after success (re-upload bundle to reinstall)
# rm -rf /usr/lib/bmsos-bundle/ipks

# Kick cellular in background (init start is non-blocking)
set_status installing uplink "Packages installed — bringing up internet…"
[ -x /etc/init.d/bmsos-modem ] && /etc/init.d/bmsos-modem start 2>/dev/null || true

set_status done complete "Install complete — refresh this page"
log "done — refresh LuCI (Services → bmsOS Gateway). Log: /tmp/bmsos-bundle-install.log"
[ -n "$FAILED" ] && log "non-critical opkg warnings:$FAILED"
exit 0
