#!/bin/bash
set -euo pipefail

PORT="${CYLONE_INSTALLER_PORT:-1748}"
DAEMON="/usr/lib/cyloneos/installer/cyloneos_installerd.py"
URL="http://127.0.0.1:${PORT}/api/health"

wait_for_api() {
	local i
	for i in $(seq 1 80); do
		if curl -sf "$URL" >/dev/null 2>&1; then
			return 0
		fi
		sleep 0.25
	done
	return 1
}

if ! wait_for_api; then
	if command -v pkexec >/dev/null 2>&1; then
		pkexec env CYLONE_INSTALLER_PORT="$PORT" python3 "$DAEMON" &
	else
		sudo env CYLONE_INSTALLER_PORT="$PORT" python3 "$DAEMON" &
	fi
	wait_for_api || {
		echo "CyloneOS Installer API startet nicht." >&2
		exit 1
	}
fi

export WLR_NO_HARDWARE_CURSORS=1
export XDG_SESSION_TYPE=wayland

BROWSER=""
for c in chromium-browser chromium google-chrome; do
	if command -v "$c" >/dev/null 2>&1; then
		BROWSER="$c"
		break
	fi
done

if [ -z "$BROWSER" ]; then
	echo "Kein Chromium-Browser gefunden." >&2
	exit 1
fi

if command -v cage >/dev/null 2>&1; then
	exec cage -m -- "$BROWSER" \
		--kiosk \
		--no-first-run \
		--disable-infobars \
		--disable-session-crashed-bubble \
		"http://127.0.0.1:${PORT}/"
fi

exec "$BROWSER" \
	--kiosk \
	--no-first-run \
	--disable-infobars \
	--disable-session-crashed-bubble \
	"http://127.0.0.1:${PORT}/"
