#!/usr/bin/env bash
# Preview the shipped Omarchy installer dashboard without building an ISO.
set -euo pipefail

simulate_install() {
  local state_file="$1"

  python - "$state_file" <<'PY'
import json
import os
import sys
import time

state_file = sys.argv[1]
started_at = time.time()
phases = [
    ("Starting installation", 0.5),
    ("Preparing live environment", 0.8),
    ("Installing Arch + Omarchy", 5.0),
    ("Configuring system", 1.2),
    ("Finalizing Limine boot", 1.0),
    ("Finalizing user", 1.0),
    ("Configuring login", 0.6),
    ("Validating boot setup", 0.8),
]


def write_state(current_phase, phase_started_at, finished_at=None):
    state = {
        "started_at": started_at,
        "phase_started_at": phase_started_at,
        "current_phase": current_phase,
    }
    if finished_at is not None:
        state["finished_at"] = finished_at

    temporary = f"{state_file}.tmp"
    with open(temporary, "w") as output:
        json.dump(state, output)
    os.replace(temporary, state_file)


for phase, duration in phases:
    phase_started_at = time.time()
    write_state(phase, phase_started_at)
    time.sleep(duration)

finished_at = time.time()
write_state("Installation complete", finished_at, finished_at)
time.sleep(0.3)
PY
}

if [[ ${1:-} == "--simulate-install" ]]; then
  (( $# == 2 )) || exit 2
  simulate_install "$2"
  exit 0
fi

if (( $# > 0 )); then
  echo "Usage: $0" >&2
  exit 2
fi

repo_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
dashboard="$repo_root/configs/airootfs/usr/local/bin/omarchy-install-dashboard"

if [[ ! -x $dashboard ]]; then
  echo "Installer dashboard is not executable: $dashboard" >&2
  exit 1
fi

if [[ -z ${OMARCHY_PATH:-} ]]; then
  for candidate in "$repo_root/../omarchy" /usr/share/omarchy; do
    if [[ -f $candidate/logo.txt ]]; then
      export OMARCHY_PATH="$candidate"
      break
    fi
  done
fi

if [[ -z ${OMARCHY_PATH:-} || ! -f $OMARCHY_PATH/logo.txt ]]; then
  echo "Unable to find Omarchy logo.txt; set OMARCHY_PATH to an Omarchy checkout." >&2
  exit 1
fi

preview_dir="$(mktemp -d)"
cleanup() {
  rm -rf "$preview_dir"
}
trap cleanup EXIT

log_file="$preview_dir/install.log"
state_file="$preview_dir/state.json"
touch "$log_file"

OMARCHY_UI_AUTO_REBOOT=no \
  "$dashboard" "$log_file" "$state_file" -- \
  "$0" --simulate-install "$state_file"
