#!/bin/sh
# Install every IPK shipped inside bmsos-inputs-bundle (offline, correct order).
# Idempotent — safe to re-run. Does NOT auto-enable the inputs service.

set -e

IPKDIR="/usr/lib/bmsos-inputs-bundle/ipks"
MARKER="/etc/bmsos-inputs-bundle.ok"

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

if [ ! -d "$IPKDIR" ]; then
	log "missing $IPKDIR"
	exit 1
fi

i=0
while { [ -e /var/lock/opkg.lock ] || [ -e /tmp/opkg.lock ]; } && [ "$i" -lt 180 ]; do
	i=$((i + 1))
	sleep 1
done
sleep 2

ORDER="
bmsos-inputs
luci-app-bmsos-inputs
"

log "installing offline Inputs packages…"

FAILED=""
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
	log "opkg install $(basename "$f")"
	if ! opkg install --force-depends --force-overwrite "$f" 2>&1; then
		if ! opkg install --force-reinstall --force-depends --force-overwrite "$f" 2>&1; then
			log "WARN failed $f"
			FAILED="$FAILED $name"
		fi
	fi
done

if [ -d /etc/uci-defaults ]; then
	for s in /etc/uci-defaults/99-bmsos-inputs; do
		[ -f "$s" ] || continue
		log "uci-defaults $(basename "$s")"
		( . "$s" ) && rm -f "$s" || true
	done
fi

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

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
[ -x /etc/init.d/uhttpd ] && /etc/init.d/uhttpd restart 2>/dev/null || true

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

date > "$MARKER"

log "done — refresh LuCI (Services → bmsOS Inputs)."
log "Then Enable from the Status tab (or: bmsos-inputs-enable)"
log "Log: /tmp/bmsos-inputs-bundle-install.log"
[ -n "$FAILED" ] && log "non-critical opkg warnings:$FAILED"
exit 0
