#!/usr/bin/env bash

# Panama's installer. Safe to re-run: every stage is idempotent, and this is
# also the upgrade path.

set -uo pipefail

PANAMA_PATH="${PANAMA_PATH:-$HOME/.local/share/Panama}"
source "$PANAMA_PATH/bin/ascii"

# ── Hostname, which is optional ──────────────────────────────────────────────
#
# Declining this used to `exit`, which aborted the ENTIRE installation. The
# prompt defaults to N, so simply pressing Enter -- the obvious thing to do when
# you do not want to rename your machine -- installed nothing at all and said
# nothing about it.
echo -e "Current hostname is: $(hostname)"
read -r -p "Do you want to change the hostname? [y/N]: " confirm_change
if [[ "$confirm_change" =~ ^[Yy]$ ]]; then
  read -r -p "Hostname: " HOST_NAME
  read -r -p "Set hostname to '$HOST_NAME'? [y/N]: " confirm_hostname
  if [[ "$confirm_hostname" =~ ^[Yy]$ ]]; then
    sudo hostnamectl set-hostname "$HOST_NAME"
    echo "Hostname set to: $(hostname)"
  else
    echo "Hostname not changed."
  fi
else
  echo "Keeping the current hostname."
fi

# ── Keep the machine awake for the duration ──────────────────────────────────
# Package installation takes long enough to hit an idle lock, and being locked
# out mid-transaction is unpleasant. Restored on every exit path, including
# failure and Ctrl-C, so an interrupted install does not leave the screen
# permanently awake.
restore_idle() {
  gsettings set org.gnome.desktop.screensaver lock-enabled true 2>/dev/null || true
  gsettings set org.gnome.desktop.session idle-delay 300 2>/dev/null || true
}
trap restore_idle EXIT INT TERM

gsettings set org.gnome.desktop.screensaver lock-enabled false 2>/dev/null || true
gsettings set org.gnome.desktop.session idle-delay 0 2>/dev/null || true

# ── Stages ───────────────────────────────────────────────────────────────────
# Each runs in its own process so strict-shell options and helper variables stay
# local to the script that owns them. A failing stage is reported and the rest
# still run: a missing optional package should not stop the dotfiles being
# linked. The summary at the end is what decides whether the install worked,
# because a failure scrolled past twenty minutes ago is a failure nobody saw.
failed=()
for script in "$PANAMA_PATH"/setup/scripts/*; do
  [[ -x "$script" ]] || continue
  stage="$(basename "$script")"
  printf '\n=== %s ===\n' "$stage"
  if ! "$script"; then
    failed+=("$stage")
    printf '!!! %s failed\n' "$stage" >&2
  fi
done

printf '\n'
if (( ${#failed[@]} == 0 )); then
  echo "Panama installed. Log out and choose the Hyprland session to start it."
else
  printf 'Panama installed with %d failed stage(s): %s\n' "${#failed[@]}" "${failed[*]}" >&2
  printf 'Re-running ./install is safe and will retry them.\n' >&2
  exit 1
fi
