#!/usr/bin/env bash
# Run as root: try bootc usr-overlay (so /usr can be written), build and install
# the full program with Meson, then launch the installed app.
#
# Usage: sudo ./scripts/test-root-bootc-config.sh
# Optional:
#   PREFIX=/usr/local sudo ./scripts/test-root-bootc-config.sh
#   BUILDDIR=builddir sudo ./scripts/test-root-bootc-config.sh

set -euo pipefail

APP_ID="io.stillhq.explore"

if [[ "${EUID:-0}" -ne 0 ]]; then
    echo "This script must run as root (e.g. sudo $0)." >&2
    exit 1
fi

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PREFIX="${PREFIX:-/usr}"
BUILDDIR="${BUILDDIR:-builddir}"
INSTALL_BIN="${PREFIX}/bin/stillexplore"

echo "Attempting bootc usr-overlay (ignored if overlay already exists or command fails)..."
if ! bootc usr-overlay; then
    echo "bootc usr-overlay failed or was skipped; continuing anyway."
fi

echo "Configuring Meson build in ${BUILDDIR}..."
if [[ -f "${REPO_ROOT}/${BUILDDIR}/build.ninja" ]]; then
    meson setup "${REPO_ROOT}/${BUILDDIR}" --reconfigure --prefix "${PREFIX}"
else
    meson setup "${REPO_ROOT}/${BUILDDIR}" --prefix "${PREFIX}"
fi

echo "Building stillexplore..."
meson compile -C "${REPO_ROOT}/${BUILDDIR}"

echo "Installing stillexplore..."
meson install -C "${REPO_ROOT}/${BUILDDIR}"

if [[ ! -x "${INSTALL_BIN}" ]]; then
    echo "Installed binary not found: ${INSTALL_BIN}" >&2
    exit 1
fi
