#!/usr/bin/env bash
set -uo pipefail

# Bootstrap entrypoint served from https://arch.zeroxclem.org/install
#
#   bash <(curl -L arch.zeroxclem.org/install)
#
# Pin a specific revision (tag, branch or commit) for a reproducible install:
#   ARCHTITUS_REF=v1.0 bash <(curl -L arch.zeroxclem.org/install)
#
# Defaults to main. It previously defaulted to the tag v2026.08.15, which was
# never actually created -- so every bootstrap run died at the checkout with
# "Could not check out 'v2026.08.15'". Tag the repo before pinning a default here.

ARCHTITUS_REF="${ARCHTITUS_REF:-main}"
ARCHTITUS_REPO="${ARCHTITUS_REPO:-https://github.com/ZeroXClem/ArchTitus}"
DEST="${ARCHTITUS_DEST:-/root/ArchTitus}"

die() { printf '\n\033[31m✖ %s\033[0m\n' "$*" >&2; exit 1; }

[[ "$(id -u)" == "0" ]] || die "Run this as root, from the Arch install ISO."

# Running this from inside a checkout is a mistake -- it would clone over the
# top of the tree you meant to run.
if [[ -f ./archtitus.sh && -d ./scripts ]]; then
    die "You are already in an ArchTitus checkout. Run 'bash ./archtitus.sh' instead."
fi

echo ":: Installing git"
pacman -Sy --noconfirm --needed git || die "Could not install git. Check your connection."

if [[ -e "$DEST" ]]; then
    echo ":: Replacing the existing checkout at $DEST"
    rm -rf "$DEST"
fi

echo ":: Cloning ArchTitus (${ARCHTITUS_REF})"
git clone --quiet "$ARCHTITUS_REPO" "$DEST" || die "Clone failed."
git -C "$DEST" checkout --quiet "$ARCHTITUS_REF" \
    || die "'${ARCHTITUS_REF}' is not a valid tag, branch or commit in ${ARCHTITUS_REPO}."

echo ":: Running ArchTitus $(git -C "$DEST" rev-parse --short HEAD)"
cd "$DEST"
# Invoked via bash rather than executed, so a lost execute bit is never fatal.
exec bash ./archtitus.sh
