#!/bin/sh
set -e

LOG=/tmp/bmsos-view-bundle-install.log
IPKDIR=/usr/lib/bmsos-view-bundle/ipks
MARKER=/etc/bmsos-view-bundle.ok
exec >>"$LOG" 2>&1
echo "=== $(date) view bundle install ==="
[ -d "$IPKDIR" ] || { echo "missing $IPKDIR"; exit 1; }

# The outer bundle's opkg process still owns this lock when postinst starts.
i=0
while { [ -e /var/lock/opkg.lock ] || [ -e /tmp/opkg.lock ]; } && [ "$i" -lt 180 ]; do
	i=$((i + 1))
	sleep 1
done
sleep 2

# Overlay cannot hold the bundle payload and cloudflared at the same time.
# Stage on tmpfs, drop the overlay copies, then install.
STAGE=/tmp/bmsos-view-bundle-ipks
rm -rf "$STAGE"
mkdir -p "$STAGE"
cp -f "$IPKDIR"/*.ipk "$STAGE/" || exit 1
rm -rf "$IPKDIR"

install_one() {
	local name="$1"
	local f
	f="$(ls -1 "$STAGE"/${name}_*.ipk 2>/dev/null | sort -V | tail -n1)"
	[ -n "$f" ] || { echo "missing $name"; return 1; }
	local ver
	ver="$(basename "$f" | sed -n "s/^${name}_\\(.*\\)\\.ipk$/\\1/p")"
	if opkg list-installed | grep -q "^${name} - ${ver}$"; then
		echo "skip $name $ver (already installed)"
		return 0
	fi
	opkg install --force-reinstall "$f" || return 1
}

install_one cloudflared || exit 1
install_one bmsos-tunnel || exit 1
install_one luci-app-bmsos-tunnel || exit 1
rm -rf "$STAGE"
date > "$MARKER"
echo DONE
