#!/bin/sh
# Stage 0 — one-click entry for a brand-new Omarchy machine.
#
#   curl -fsSL https://boot.levantarlabs.com | sh
#
# Asks for: the sudo password, then the secrets-bundle passphrase (both via /dev/tty,
# so piping this script into sh is fine). Then: restores ~/.tokens, ~/.env and SSH
# key, clones the private dotfiles repo using the GitHub token from the bundle
# (never placed in a URL), runs FORCE=1 ./install/main.sh and ./install/test.sh.
#
# Env overrides (mostly for tests):
#   BOOT_URL=https://boot.levantarlabs.com   where the secrets bundle lives
#   DOTFILES_REPO=https://github.com/ittisafur/dotfiles-arch.git
#   DOTFILES_DIR=$HOME/dotfiles
#   BOOTSTRAP_SKIP="pkgs import gh clone run"   any of these steps, space separated
#   BOOTSTRAP_BUNDLE=FILE                       use a local bundle instead of BOOT_URL
#
# Manual by nature afterwards: gcloud auth login (x3), bw login / op signin,
# one re-login for the docker group.

set -eu
umask 077

BOOT_URL=${BOOT_URL:-https://boot.levantarlabs.com}
DOTFILES_REPO=${DOTFILES_REPO:-https://github.com/ittisafur/dotfiles-arch.git}
DOTFILES_DIR=${DOTFILES_DIR:-$HOME/dotfiles}
BOOTSTRAP_SKIP=${BOOTSTRAP_SKIP:-}

log() { printf '%s\n' "$*"; }
warn() { printf 'warn: %s\n' "$*" >&2; }
die() { printf 'error: %s\n' "$*" >&2; exit 1; }
skip() { for _s in $BOOTSTRAP_SKIP; do [ "$_s" = "$1" ] && return 0; done; return 1; }

KEEPALIVE_PID=
cleanup() {
  [ -n "$KEEPALIVE_PID" ] && kill "$KEEPALIVE_PID" 2>/dev/null || true
  [ -n "${TMPD:-}" ] && rm -rf "$TMPD"
}
trap cleanup EXIT INT TERM

# ---- 1. sudo + packages ------------------------------------------------------
if skip pkgs; then
  log "skip: pkgs"
else
  command -v sudo >/dev/null 2>&1 || die "sudo missing"
  log "==> sudo (needed once; kept alive for the whole run)"
  sudo -v || die "sudo failed"
  ( while :; do sleep 50; sudo -n -v 2>/dev/null || exit 0; done ) &
  KEEPALIVE_PID=$!
  command -v omarchy >/dev/null 2>&1 || die "this installer targets Omarchy (omarchy CLI not found)"
  log "==> base packages"
  for _p in age git stow rclone github-cli; do
    if pacman -Q "$_p" >/dev/null 2>&1; then log "present: $_p"; else omarchy pkg add "$_p" || die "failed to install $_p"; fi
  done
fi

command -v age >/dev/null 2>&1 || die "age is required"
command -v curl >/dev/null 2>&1 || die "curl is required"

# ---- 2. restore secrets (same rules as bin/.local/bin/secrets-import) -------------
import_secrets() {
  TMPD=$(mktemp -d)
  if [ -n "${BOOTSTRAP_BUNDLE:-}" ]; then
    cp "$BOOTSTRAP_BUNDLE" "$TMPD/secrets.age"
  else
    curl -fsSL "$BOOT_URL/secrets.age" -o "$TMPD/secrets.age" || die "could not download bundle from $BOOT_URL"
  fi
  [ -s "$TMPD/secrets.age" ] || die "empty bundle"
  age -d -o "$TMPD/bundle.tar" "$TMPD/secrets.age" || die "decryption failed (wrong passphrase?)"
  tar -tf "$TMPD/bundle.tar" >"$TMPD/names" || die "bundle is not a tar archive"
  tar -tvf "$TMPD/bundle.tar" | cut -c1 | grep -qE '[lh]' && die "refusing bundle with links"
  while IFS= read -r _n; do
    _n=${_n%/}
    case "$_n" in
      .tokens|.tokens/*|.env|.pgpass|.my.cnf|.ssh|.ssh/id_ed25519|.ssh/id_ed25519.pub|.ssh/config) ;;
      *) die "refusing unexpected path in bundle: $_n" ;;
    esac
    case "/$_n/" in */../*) die "refusing path traversal: $_n" ;; esac
  done <"$TMPD/names"
  tar -C "$HOME" -xf "$TMPD/bundle.tar" --no-same-owner --skip-old-files
  [ -d "$HOME/.tokens" ] && { chmod 700 "$HOME/.tokens"; find "$HOME/.tokens" -type f -exec chmod 600 {} +; }
  [ -d "$HOME/.ssh" ] && { chmod 700 "$HOME/.ssh"; find "$HOME/.ssh" -type f -exec chmod 600 {} +; chmod 644 "$HOME/.ssh/id_ed25519.pub" 2>/dev/null || true; }
  for _f in .env .pgpass .my.cnf; do [ -f "$HOME/$_f" ] && chmod 600 "$HOME/$_f"; done
  log "restored $(grep -vc '/$' "$TMPD/names") files (names not shown; values never printed)"
}

if skip import; then log "skip: import"; else
  log "==> restoring secrets (passphrase prompt)"
  import_secrets
fi

# ---- 3. GitHub auth + clone --------------------------------------------------
if skip gh; then log "skip: gh"; else
  if [ -r "$HOME/.tokens/.github" ] && command -v gh >/dev/null 2>&1; then
    log "==> gh auth (token from bundle)"
    gh auth login --with-token <"$HOME/.tokens/.github" || warn "gh auth login failed"
    gh auth setup-git || warn "gh auth setup-git failed"
  else
    warn "no ~/.tokens/.github or gh — clone of a private repo may fail"
  fi
fi

if skip clone; then log "skip: clone"; else
  if [ -d "$DOTFILES_DIR/.git" ]; then
    log "dotfiles present: $DOTFILES_DIR (pull --ff-only)"
    git -C "$DOTFILES_DIR" pull --ff-only || warn "git pull failed; continuing with local tree"
  else
    log "==> clone $DOTFILES_REPO -> $DOTFILES_DIR"
    git clone "$DOTFILES_REPO" "$DOTFILES_DIR" || die "clone failed"
  fi
fi

# ---- 4. install + test -------------------------------------------------------
if skip run; then log "skip: run"; else
  cd "$DOTFILES_DIR"
  FORCE=1 ./install/main.sh || warn "main.sh reported failures (see its summary/log)"
  ./install/test.sh || warn "test.sh reported failures"
fi

log "stage 0 done. Manual: gcloud auth login (x3), bw login / op signin, re-login for docker group."
