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

write_simulation_state() {
  local state_file="$1" started_at="$2" phase_started_at="$3" current_phase="$4"
  local finished_at="${5:-null}" temporary="${state_file}.tmp"

  jq -n \
    --argjson started_at "$started_at" \
    --argjson phase_started_at "$phase_started_at" \
    --arg current_phase "$current_phase" \
    --argjson finished_at "$finished_at" \
    '{
      started_at: $started_at,
      phase_started_at: $phase_started_at,
      current_phase: $current_phase
    } + if $finished_at == null then {} else {finished_at: $finished_at} end' \
    >"$temporary"
  mv -f -- "$temporary" "$state_file"
}

simulate_install() {
  local state_file="$1"
  local started_at="$EPOCHREALTIME"
  local phase phase_started_at finished_at duration i
  local -a 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
  )

  for ((i = 0; i < ${#phases[@]}; i += 2)); do
    phase="${phases[i]}"
    duration="${phases[i + 1]}"
    phase_started_at="$EPOCHREALTIME"
    write_simulation_state "$state_file" "$started_at" "$phase_started_at" "$phase"
    sleep "$duration"
  done

  finished_at="$EPOCHREALTIME"
  write_simulation_state "$state_file" "$started_at" "$finished_at" "Installation complete" "$finished_at"
  sleep 0.3
}

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"
