#!/bin/bash
# bootstrap.sh — one-line installer for jeanphilipper's chezmoi dotfiles.
# Public: contains no secrets.
#
#   curl -fsLS https://dotfiles.jean-philipper.fr/init | bash
#
# The age private key is handed over by a small web page at /keys that sits
# behind Cloudflare Access (SSO + MFA). The script opens that page, you copy the
# key and paste it at the hidden prompt. On a headless machine the URL is
# printed instead.
set -euo pipefail

if [ -z "${BASH_VERSION:-}" ]; then
  echo "error: this installer must run under bash, not sh." >&2
  echo "  run: curl -fsLS https://dotfiles.jean-philipper.fr/init | bash" >&2
  exit 1
fi

# --- Public configuration (overridable via environment for testing) ---------
GITHUB_USER="${GITHUB_USER:-jeanphilipper}"
AGE_KEY_PATH="${AGE_KEY_PATH:-${HOME}/.config/chezmoi/key.txt}"
KEY_PAGE_URL="${KEY_PAGE_URL:-https://dotfiles.jean-philipper.fr/keys}"

# Progress goes to stderr so that functions returning values via stdout stay clean.
info() { printf '\033[1;34m==>\033[0m %s\n' "$*" >&2; }
warn() { printf '\033[1;33m warn\033[0m %s\n' "$*" >&2; }
die() {
  printf '\033[1;31merror\033[0m %s\n' "$*" >&2
  exit 1
}

# ---------------------------------------------------------------------------
# 1. Homebrew
# ---------------------------------------------------------------------------
install_brew() {
  if command -v brew >/dev/null 2>&1; then
    info "Homebrew already installed"
    return
  fi

  info "Installing Homebrew..."
  NONINTERACTIVE=1 /bin/bash -c \
    "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

  local brew_bin
  if [[ -x /opt/homebrew/bin/brew ]]; then
    brew_bin=/opt/homebrew/bin/brew
  elif [[ -x /home/linuxbrew/.linuxbrew/bin/brew ]]; then
    brew_bin=/home/linuxbrew/.linuxbrew/bin/brew
  elif [[ -x /usr/local/bin/brew ]]; then
    brew_bin=/usr/local/bin/brew
  else
    die "Homebrew installed but the brew binary could not be located"
  fi
  eval "$("${brew_bin}" shellenv)"

  case "${SHELL:-}" in
    */zsh) printf '\n%s\n' "eval \"\$(${brew_bin} shellenv)\"" >>"${HOME}/.zshrc" ;;
    */bash) printf '\n%s\n' "eval \"\$(${brew_bin} shellenv)\"" >>"${HOME}/.bashrc" ;;
  esac
}

# ---------------------------------------------------------------------------
# 2. chezmoi + GitHub CLI
# ---------------------------------------------------------------------------
install_packages() {
  info "Installing chezmoi and gh via Homebrew..."
  brew install chezmoi gh
}

# ---------------------------------------------------------------------------
# 3. age key
# ---------------------------------------------------------------------------
open_url() {
  if command -v open >/dev/null 2>&1; then
    open "$1"
  elif command -v xdg-open >/dev/null 2>&1; then
    xdg-open "$1" >/dev/null 2>&1
  else
    return 1
  fi
}

# Open the Access-protected page so the user can copy the key. Best effort: if
# there is no browser (e.g. SSH), just print the URL and let the paste prompt
# handle the rest.
show_key_page() {
  if [[ -n "${SSH_CONNECTION:-}" ]]; then
    info "Open this URL in a browser on any device you trust:"
    printf '    %s\n' "${KEY_PAGE_URL}" >&2
    return
  fi
  info "Opening ${KEY_PAGE_URL} — sign in, then copy the key."
  if ! open_url "${KEY_PAGE_URL}"; then
    info "Could not open a browser automatically. Visit:"
    printf '    %s\n' "${KEY_PAGE_URL}" >&2
  fi
}

prompt_age_key() {
  echo >&2
  echo "Paste your age private key (AGE-SECRET-KEY-1...) and press Enter." >&2
  echo "Input is hidden and never leaves this machine." >&2

  # The installer is normally run as `curl ... | bash`, so stdin is the pipe,
  # not the terminal. Read from the controlling terminal so the prompt actually
  # waits for input (and so a piped script can never feed its own key). Fall
  # back to stdin when there is no terminal, e.g. tests piping a key in.
  local tty=""
  if { true >/dev/tty; } 2>/dev/null; then
    tty="/dev/tty"
  fi

  local key="" confirm=""
  while [[ -z "${key}" ]]; do
    if [[ -n "${tty}" ]]; then
      read -rsp "age key: " key <"${tty}"
      echo >&2
    elif ! read -rsp "age key: " key; then
      # No terminal and nothing on stdin: let the caller report and exit, since
      # a `die` here would only kill the command-substitution subshell.
      warn "No terminal available and no key on stdin."
      return 1
    fi

    if [[ -z "${key}" ]]; then
      warn "No key entered."
    elif [[ "${key}" != AGE-SECRET-KEY-1* ]]; then
      warn "That does not look like an age private key (expected AGE-SECRET-KEY-1...)."
      if [[ -n "${tty}" ]]; then
        read -rp "Use it anyway? [y/N] " confirm <"${tty}"
      else
        read -rp "Use it anyway? [y/N] " confirm || confirm=""
      fi
      [[ "${confirm}" =~ ^[Yy]$ ]] || key=""
    fi
  done
  printf '%s\n' "${key}"
}

write_age_key() {
  local key="$1"
  mkdir -p "$(dirname "${AGE_KEY_PATH}")"
  (
    umask 077
    printf '%s\n' "${key}" >"${AGE_KEY_PATH}"
  )
  chmod 600 "${AGE_KEY_PATH}"
  unset key
  info "age key written to ${AGE_KEY_PATH}"
}

ensure_age_key() {
  if [[ -s "${AGE_KEY_PATH}" ]]; then
    info "age key already present at ${AGE_KEY_PATH} (leaving untouched)"
    return
  fi

  show_key_page

  local key=""
  if ! key="$(prompt_age_key)"; then
    die "Could not read the age key. Get it from ${KEY_PAGE_URL} and run the installer from a terminal."
  fi
  [[ -n "${key}" ]] || die "No age key provided."
  write_age_key "${key}"
}

# ---------------------------------------------------------------------------
# 4. Deploy dotfiles
# ---------------------------------------------------------------------------
init_dotfiles() {
  info "Initializing dotfiles from github.com/${GITHUB_USER}/dotfiles..."
  chezmoi init --apply "${GITHUB_USER}"
}

main() {
  install_brew
  install_packages
  ensure_age_key
  init_dotfiles
  info "Done! Restart your shell."
}

# Run only when executed directly (not when sourced for testing).
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  main "$@"
fi
