#!/usr/bin/env bash

# Panama's front door: the one command a fresh Fedora machine needs.
#
#   bash <(curl -fsSL https://git.gbrown.org/gib/Panama/raw/branch/main/boot)
#
# Deliberately dumb, because a copy of this script leaves the repository the
# moment somebody curls it -- nothing here can be fixed by re-running
# ./install, so there is as little here as possible: get git, get the clone,
# hand off. Everything with judgment in it lives in `install`, which is also
# where re-runs and upgrades already work.

set -euo pipefail

REPO_URL="https://git.gbrown.org/gib/Panama.git"
PANAMA_PATH="${PANAMA_PATH:-$HOME/.local/share/Panama}"
export PANAMA_PATH

# Root would put the clone and every dotfile in root's home and run the
# desktop setup for the wrong user. sudo is used inside where it is needed.
if [[ "$(id -u)" -eq 0 ]]; then
  echo "Run this as your own user, not root: the install configures YOUR desktop." >&2
  exit 1
fi

# Panama assumes Fedora's repositories, package names, and GNOME base install.
if ! grep -qi '^ID=fedora' /etc/os-release 2>/dev/null; then
  echo "This looks like something other than Fedora; Panama only supports Fedora Workstation." >&2
  exit 1
fi

# git is the one dependency the clone itself needs. Everything else -- gum
# included -- is bootstrapped by `install`.
if ! command -v git >/dev/null 2>&1; then
  echo "Installing git, which the clone needs"
  sudo dnf install -y git
fi

if [[ -d "$PANAMA_PATH/.git" ]]; then
  # An existing clone makes this the recovery command too. Only a fast-forward:
  # local work is never rewritten, and a diverged clone still installs from
  # what it has rather than stopping someone mid-repair.
  echo "Panama is already cloned at $PANAMA_PATH; updating"
  git -C "$PANAMA_PATH" pull --ff-only \
    || echo "Could not fast-forward; installing from the clone as it is" >&2
else
  git clone "$REPO_URL" "$PANAMA_PATH"
fi

# `curl | bash` and `bash <(curl ...)` can leave stdin as the pipe, and the
# first thing install runs is the interview, which has to be able to ask.
# Reattach the terminal when there is one; without one the interview will say
# so itself.
# The probe actually opens /dev/tty rather than testing -r: a process with no
# controlling terminal passes -r and then fails the redirect.
if [[ ! -t 0 ]] && (exec </dev/tty) 2>/dev/null; then
  exec "$PANAMA_PATH/install" </dev/tty
fi
exec "$PANAMA_PATH/install"
