#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────
# Alvin Bot — One-Line Installer
# Usage: curl -fsSL https://unpkg.com/alvin-bot/install.sh | bash
#    or: curl -fsSL https://cdn.jsdelivr.net/npm/alvin-bot/install.sh | bash
#
# Designed for a *fresh* machine. It needs NOTHING preinstalled — no
# Homebrew, no Xcode Command Line Tools, no sudo, no system Node. If a
# usable Node (22 or newer) is already on PATH it is reused; otherwise a
# self-contained Node runtime is downloaded into ~/.alvin-bot/runtime and
# alvin-bot is installed into it. A system Node counts as usable from 22 on
# (not 23): the database module ships ready builds only for 22, 24, 25 and
# 26 — on 18, 20 or 23 npm would have to compile it, which fails without a
# compiler.
#
# It does NOT clone the git repo and never touches system directories.
# `~/.alvin-bot/` is the per-user data dir (env, memory, logs, runtime).
#
# With the bundled runtime, the `alvin-bot` command is a small launcher in
# ~/.alvin-bot/bin that starts the runtime's Node directly — it works without
# `node` on PATH (a fresh terminal, launchd, cron). npm never owns that file,
# so updates leave it alone. Running the installer again repairs an install:
# package, launcher and the PATH line in your shell profile.
#
# Environment (all optional):
#   NO_COLOR=1               plain output without colours
#   ALVIN_LANG=de|en         language of the installer (default: from LANG)
# For tests only — not needed for a normal install:
#   ALVIN_INSTALL_TARBALL    install this package tarball instead of the
#                            release from the npm registry
#   ALVIN_INSTALL_TTY        read the "set up now?" answer from this file
#                            instead of /dev/tty
# ─────────────────────────────────────────────────────────────

# `curl … | sh` runs dash on Debian/Ubuntu, which stops at `set -o pipefail`
# with a cryptic error. This line is plain POSIX on purpose.
if [ -z "${BASH_VERSION:-}" ]; then
  echo "Please run the installer with bash:  curl -fsSL https://unpkg.com/alvin-bot/install.sh | bash" >&2
  exit 1
fi

set -euo pipefail

MIN_NODE_VERSION=22
NODE_MAJOR=22                       # portable runtime line (current LTS)
RUNTIME_DIR="${HOME:-}/.alvin-bot/runtime"
STARTER="${HOME:-}/.alvin-bot/bin/alvin-bot"
STARTER_MARK="# alvin-bot launcher (written by install.sh)"
NPM_PREFIX="${HOME:-}/.npm-global"
STEPS_TOTAL=4

# ─── Look & language ────────────────────────────────────────

# Colours only on a terminal, never with NO_COLOR (https://no-color.org) or
# TERM=dumb. Piped through `curl | bash`, stdout is still the terminal.
setup_colors() {
  if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-}" != "dumb" ]; then
    RED=$'\033[0;31m'; GREEN=$'\033[0;32m'; YELLOW=$'\033[1;33m'
    BLUE=$'\033[0;34m'; BOLD=$'\033[1m'; DIM=$'\033[2m'; NC=$'\033[0m'
    FANCY=1
  else
    RED=''; GREEN=''; YELLOW=''; BLUE=''; BOLD=''; DIM=''; NC=''
    FANCY=0
  fi
}

detect_lang() {
  local l="${ALVIN_LANG:-${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}}"
  case "$l" in de*|DE*) UI_LANG=de ;; *) UI_LANG=en ;; esac
}

# say "english" "deutsch" — prints the text for the current language.
say() { if [ "${UI_LANG:-en}" = de ]; then printf '%s' "$2"; else printf '%s' "$1"; fi; }

info()  { printf '%s\n' "${BLUE}ℹ${NC}  $*"; }
ok()    { printf '%s\n' "${GREEN}✔${NC}  $*"; }
warn()  { printf '%s\n' "${YELLOW}⚠${NC}  $*"; }
log_hint() {
  if [ -n "${LOG_FILE:-}" ] && [ -s "$LOG_FILE" ]; then
    printf '\n%s\n' "   $(say "Last lines of the log:" "Letzte Zeilen des Protokolls:")" >&2
    tail -n 12 "$LOG_FILE" | sed 's/^/     /' >&2
    printf '\n%s\n' "   $(say "Full log:" "Vollständiges Protokoll:") ${BOLD}$LOG_FILE${NC}" >&2
  fi
}
fail()  {
  printf '%s\n' "${RED}✘${NC}  $*" >&2
  log_hint
  printf '%s\n' "   $(say "Fix the cause and run the installer again — it picks up where it stopped." \
                        "Ursache beheben und den Installer erneut starten — er setzt dort wieder an.")" >&2
  exit 1
}

# Write the absolute path the way a user can paste it: $HOME as ~ is not
# safe inside quotes, so keep it absolute and quote it only when needed.
shell_quote() {
  case "$1" in
    *[!A-Za-z0-9_./~:+-]*) printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")" ;;
    *) printf '%s' "$1" ;;
  esac
}

# ─── Temp dirs, Ctrl-C ──────────────────────────────────────

# Temp dirs live in ~/.alvin-bot with a fixed prefix. Only those are ever
# removed recursively, and only after checking the prefix again.
STAGE_PREFIX="${HOME:-}/.alvin-bot/.runtime-new."
STAGE_DIR=''
remove_stage() {
  local d="$STAGE_DIR"
  STAGE_DIR=''
  [ -n "$d" ] || return 0
  case "$d" in "$STAGE_PREFIX"?*) rm -rf -- "$d" ;; esac
}

# The running npm/curl is started in its own process group (set -m in
# run_logged), so Ctrl-C reaches only the installer — which then stops
# exactly that group (our own child, by its PID = PGID) before leaving.
CHILD_PID=''
on_abort() {
  trap - INT TERM
  if [ -n "$CHILD_PID" ]; then
    kill -TERM -- "-$CHILD_PID" 2>/dev/null || kill -TERM "$CHILD_PID" 2>/dev/null || true
    wait "$CHILD_PID" 2>/dev/null || true
    CHILD_PID=''
  fi
  [ "${FANCY:-0}" = 1 ] && printf '\r\033[K'
  remove_stage
  printf '\n%s\n' "${YELLOW}⚠${NC}  $(say "Installation cancelled. Run the installer again to finish it." \
                                           "Installation abgebrochen. Den Installer erneut starten, um sie abzuschließen.")" >&2
  [ -n "${LOG_FILE:-}" ] && printf '%s\n' "   $(say "Log:" "Protokoll:") $LOG_FILE" >&2
  exit 130
}

# ─── Steps with timing ──────────────────────────────────────

STEP_NO=0; STEP_TITLE=''; STEP_T0=0
step_begin() {
  STEP_NO=$1; STEP_TITLE=$2; STEP_T0=$SECONDS
  if [ "$FANCY" = 1 ]; then
    printf '  %s %s …' "${DIM}[$STEP_NO/$STEPS_TOTAL]${NC}" "$STEP_TITLE"
  else
    printf '  [%s/%s] %s …\n' "$STEP_NO" "$STEPS_TOTAL" "$STEP_TITLE"
  fi
}
step_end() {
  local detail="$1" dur=$((SECONDS - STEP_T0))
  [ "$FANCY" = 1 ] && printf '\r\033[K'
  printf '  %s %s %s %s\n' "${GREEN}✔${NC}" "${DIM}[$STEP_NO/$STEPS_TOTAL]${NC}" \
    "${BOLD}$STEP_TITLE${NC}${detail:+ — $detail}" "${DIM}(${dur} s)${NC}"
}
step_fail() {
  [ "$FANCY" = 1 ] && printf '\r\033[K'
  printf '  %s %s %s\n' "${RED}✘${NC}" "${DIM}[$STEP_NO/$STEPS_TOTAL]${NC}" "${BOLD}$STEP_TITLE${NC}"
  remove_stage
  fail "$@"
}

# Run a command with all its output in the log, in its own process group
# and with stdin from /dev/null (ours is the piped script under curl | bash).
# On a terminal a small spinner shows it is alive.
run_logged() {
  local label="$1"; shift
  printf '\n$ %s\n' "$*" >> "$LOG_FILE"
  local rc=0 i=0
  set -m
  "$@" < /dev/null >> "$LOG_FILE" 2>&1 &
  CHILD_PID=$!
  set +m
  if [ "$FANCY" = 1 ]; then
    local frames=('⠋' '⠙' '⠹' '⠸' '⠼' '⠴' '⠦' '⠧' '⠇' '⠏')
    while kill -0 "$CHILD_PID" 2>/dev/null; do
      printf '\r\033[K  %s %s %s' "${BLUE}${frames[$((i % 10))]}${NC}" "${DIM}[$STEP_NO/$STEPS_TOTAL]${NC}" "$STEP_TITLE${label:+ — $label}"
      i=$((i + 1))
      sleep 0.1
    done
  fi
  wait "$CHILD_PID" || rc=$?
  CHILD_PID=''
  return "$rc"
}

start_log() {
  local dir="$HOME/.alvin-bot/logs"
  if mkdir -p "$dir" 2>/dev/null; then
    LOG_FILE="$dir/install-$(date +%Y%m%d-%H%M%S).log"
    : > "$LOG_FILE"
  else
    # Never a predictable name in a shared /tmp (a planted symlink would be followed).
    LOG_FILE="$(mktemp "${TMPDIR:-/tmp}/alvin-install.XXXXXX")" || LOG_FILE=/dev/null
  fi
}

# ─── Shell profile (PATH) ───────────────────────────────────

# The login shell's name. An empty $SHELL (Docker, some CI) means the
# system default: zsh on macOS, bash elsewhere.
login_shell() {
  local s="${SHELL##*/}"
  if [ -z "$s" ]; then
    if [ "${OS:-}" = "macOS" ]; then s=zsh; else s=bash; fi
  fi
  printf '%s' "$s"
}

# The profile the login shell really reads.
#   zsh → ~/.zshrc
#   bash on macOS (Terminal opens login shells): the FIRST existing of
#     ~/.bash_profile, ~/.bash_login, ~/.profile — bash reads only that one,
#     so creating ~/.bash_profile next to a ~/.profile would hide the latter.
#   bash on Linux → ~/.bashrc;  sh/dash/ksh → ~/.profile
#   fish → none here (conf.d file below)
primary_rc() {
  local f
  case "$(login_shell)" in
    bash)
      if [ "${OS:-}" = "macOS" ]; then
        for f in .bash_profile .bash_login .profile; do
          [ -e "$HOME/$f" ] && { echo "$HOME/$f"; return 0; }
        done
        echo "$HOME/.bash_profile"
      else
        echo "$HOME/.bashrc"
      fi ;;
    sh|dash|ksh) echo "$HOME/.profile" ;;
    fish|csh|tcsh) echo "" ;;
    *)    echo "$HOME/.zshrc" ;;   # zsh, and the modern macOS default
  esac
}

# Append a line to the user's shell profiles, guarded by a marker so re-runs
# don't duplicate it: the login shell's own profile (created if missing — a
# fresh macOS account often has no ~/.zshrc), plus every other profile that
# already exists. Records what it touched in RC_FILES, unwritable files
# (e.g. a read-only symlink from Nix/home-manager) in RC_SKIPPED.
RC_FILES=''; RC_SKIPPED=''
persist_path_line() {
  local line="$1" marker="$2" rc primary seen=''
  primary="$(primary_rc)"
  for rc in "$primary" "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do
    [ -n "$rc" ] || continue
    if [ "$rc" != "$primary" ] && [ ! -e "$rc" ]; then continue; fi
    case " $seen " in *" $rc "*) continue ;; esac
    seen="$seen $rc"
    if [ ! -e "$rc" ] && [ "$rc" = "$HOME/.bash_profile" ]; then
      # A new ~/.bash_profile must not hide ~/.profile (should one appear later).
      { printf '# Read ~/.profile too: bash reads only the first of .bash_profile/.bash_login/.profile.\n[ -r "$HOME/.profile" ] && . "$HOME/.profile"\n' >> "$rc"; } 2>/dev/null || true
    fi
    if ! grep -qF "$marker" "$rc" 2>/dev/null; then
      if ! { printf '\n# %s\n%s\n' "$marker" "$line" >> "$rc"; } 2>/dev/null; then
        case " $RC_SKIPPED " in *" $rc "*) ;; *) RC_SKIPPED="$RC_SKIPPED $rc" ;; esac
        continue
      fi
    fi
    case " $RC_FILES " in *" $rc "*) ;; *) RC_FILES="$RC_FILES $rc" ;; esac
  done
}

# fish reads none of the files above. Only when fish is in use. $1 is put in
# front of PATH, an optional $2 at its end.
persist_fish_path() {
  local first="$1" last="${2:-}" conf="$HOME/.config/fish/conf.d/alvin-bot.fish"
  if [ "$(login_shell)" != "fish" ] && [ ! -d "$HOME/.config/fish" ]; then return 0; fi
  mkdir -p "${conf%/*}" 2>/dev/null || { RC_SKIPPED="$RC_SKIPPED $conf"; return 0; }
  {
    printf '# alvin-bot (written by install.sh)\n'
    printf 'if not contains -- "%s" $PATH\n    set -gx PATH "%s" $PATH\nend\n' "$first" "$first"
    [ -n "$last" ] && printf 'if not contains -- "%s" $PATH\n    set -gx PATH $PATH "%s"\nend\n' "$last" "$last"
  } > "$conf" 2>/dev/null || { RC_SKIPPED="$RC_SKIPPED $conf"; return 0; }
  RC_FILES="$RC_FILES $conf"
}

pretty_list() {
  local out='' f
  for f in $1; do
    case "$f" in "$HOME"/*) f="~${f#"$HOME"}" ;; esac
    out="$out${out:+, }$f"
  done
  printf '%s' "$out"
}

# ─── OS / Arch detection ───────────────────────────────────

detect_platform() {
  case "$(uname -s)" in
    Darwin*) OS="macOS"; NPLAT="darwin" ;;
    Linux*)
      if grep -qi microsoft /proc/version 2>/dev/null; then OS="WSL"; else OS="Linux"; fi
      NPLAT="linux"
      ;;
    *) step_fail "$(say "Unsupported OS: $(uname -s). Use macOS, Linux, or WSL." \
                       "Nicht unterstütztes Betriebssystem: $(uname -s). Bitte macOS, Linux oder WSL.")" ;;
  esac
  case "$(uname -m)" in
    arm64|aarch64) NARCH="arm64" ;;
    x86_64|amd64)  NARCH="x64" ;;
    *) step_fail "$(say "Unsupported CPU architecture: $(uname -m)." "Nicht unterstützte CPU-Architektur: $(uname -m).")" ;;
  esac
}

# ─── Node bootstrap (zero prereqs) ─────────────────────────

node_major() { "$1" -v 2>/dev/null | sed 's/^v//' | cut -d. -f1; }

# A Node version the package installs on without a compiler: 22 or newer,
# but not 23 (no ready builds of the database module for it).
good_major() {
  [ -n "$1" ] && [ "$1" -ge "$MIN_NODE_VERSION" ] 2>/dev/null && [ "$1" != 23 ]
}

# True if a usable *system* Node is already callable. Not when that node is
# our own runtime (a terminal that already loaded the PATH line) and not when
# alvin-bot already lives in the runtime: then this run is a repair of the
# portable install — prefix pinned, launcher rewritten.
have_good_node() {
  command -v node >/dev/null 2>&1 || return 1
  [ "$(command -v node)" = "$RUNTIME_DIR/bin/node" ] && return 1
  [ -d "$RUNTIME_DIR/lib/node_modules/alvin-bot" ] && return 1
  good_major "$(node_major node)"
}

# Download Node and put ONLY Node's own files into the runtime: bin/node,
# bin/npm, bin/npx, bin/corepack, lib/node_modules/{npm,corepack},
# include/node. Everything else in ~/.alvin-bot/runtime stays — other global
# packages (alvin-bot, pm2, …) and anything a user keeps there (e.g. node/,
# current/, python/, which a launchd service may run from). Never a
# recursive delete of the runtime itself.
download_node() {
  local base="https://nodejs.org/dist/latest-v${NODE_MAJOR}.x" tarname name
  # The directory-listing row prints the filename twice (href + link text),
  # so grep -o yields two hits — sed picks the first. sed reads the whole
  # (tiny) stream, so nothing closes early and pipefail stays happy.
  tarname=$(curl -fsSL "$base/" 2>>"$LOG_FILE" \
    | grep -oE "node-v${NODE_MAJOR}\.[0-9]+\.[0-9]+-${NPLAT}-${NARCH}\.tar\.gz" \
    | sed -n '1p') || true
  [ -n "$tarname" ] || step_fail "$(say "Could not find a Node $NODE_MAJOR build for ${NPLAT}-${NARCH} on nodejs.org (offline?)." \
                                        "Kein Node-$NODE_MAJOR-Paket für ${NPLAT}-${NARCH} auf nodejs.org gefunden (offline?).")"

  mkdir -p "$HOME/.alvin-bot"
  STAGE_DIR="$(mktemp -d "${STAGE_PREFIX}XXXXXX")" \
    || step_fail "$(say "Could not create a temporary folder in ~/.alvin-bot." "Kein temporärer Ordner in ~/.alvin-bot möglich.")"
  case "$STAGE_DIR" in "$STAGE_PREFIX"?*) ;; *) STAGE_DIR=''; step_fail "unexpected temp dir" ;; esac

  run_logged "${tarname%.tar.gz}" curl -fsSL -o "$STAGE_DIR/node.tar.gz" "$base/$tarname" \
    || step_fail "$(say "Download failed: $base/$tarname" "Download fehlgeschlagen: $base/$tarname")"
  mkdir -p "$STAGE_DIR/x"
  tar -xzf "$STAGE_DIR/node.tar.gz" -C "$STAGE_DIR/x" --strip-components=1 >>"$LOG_FILE" 2>&1 \
    && [ -x "$STAGE_DIR/x/bin/node" ] \
    || step_fail "$(say "Failed to extract the Node runtime." "Die Node-Laufzeit ließ sich nicht entpacken.")"

  mkdir -p "$RUNTIME_DIR/bin" "$RUNTIME_DIR/lib/node_modules" "$RUNTIME_DIR/include"
  for name in npm corepack; do
    [ -d "$STAGE_DIR/x/lib/node_modules/$name" ] || continue
    rm -rf -- "${RUNTIME_DIR:?}/lib/node_modules/$name"
    mv "$STAGE_DIR/x/lib/node_modules/$name" "$RUNTIME_DIR/lib/node_modules/$name"
  done
  if [ -d "$STAGE_DIR/x/include/node" ]; then
    rm -rf -- "${RUNTIME_DIR:?}/include/node"
    mv "$STAGE_DIR/x/include/node" "$RUNTIME_DIR/include/node"
  fi
  for name in node npm npx corepack; do
    [ -e "$STAGE_DIR/x/bin/$name" ] || [ -L "$STAGE_DIR/x/bin/$name" ] || continue
    rm -f -- "$RUNTIME_DIR/bin/$name"
    mv "$STAGE_DIR/x/bin/$name" "$RUNTIME_DIR/bin/$name"
  done
  remove_stage
}

ensure_node() {
  step_begin 2 "$(say "Node.js runtime" "Node.js-Laufzeit")"
  if have_good_node; then
    USED_PORTABLE_NODE=0
    NODE_BIN="$(command -v node)"
    command -v npm >/dev/null 2>&1 || step_fail "$(say "npm missing — your Node install looks broken." "npm fehlt — die Node-Installation ist unvollständig.")"
    step_end "$(node -v) $(say "(already installed)" "(bereits vorhanden)")"
    return 0
  fi

  USED_PORTABLE_NODE=1
  local how
  # Reuse an existing good runtime from a previous run — only if its npm
  # works too; otherwise every re-run would stop at "npm missing".
  if [ -x "$RUNTIME_DIR/bin/node" ] && good_major "$(node_major "$RUNTIME_DIR/bin/node")" && \
     [ -x "$RUNTIME_DIR/bin/npm" ] && \
     PATH="$RUNTIME_DIR/bin:$PATH" "$RUNTIME_DIR/bin/npm" -v >/dev/null 2>&1; then
    how="$(say "reused" "wiederverwendet")"
  else
    download_node
    how="$(say "downloaded" "heruntergeladen")"
  fi
  export PATH="$RUNTIME_DIR/bin:$PATH"
  NODE_BIN="$RUNTIME_DIR/bin/node"
  [ -x "$NODE_BIN" ] && "$NODE_BIN" -v >/dev/null 2>&1 \
    || step_fail "$(say "Node runtime installed but not callable." "Node-Laufzeit installiert, aber nicht aufrufbar.")"
  [ -x "$RUNTIME_DIR/bin/npm" ] || step_fail "$(say "npm missing in the Node runtime." "npm fehlt in der Node-Laufzeit.")"
  step_end "$("$NODE_BIN" -v) ($how, ~/.alvin-bot/runtime)"
}

# ─── User-owned npm prefix (no-sudo fallback) ──────────────

# Only used when a *system* Node's global prefix isn't writable. The
# portable runtime's own prefix is already user-owned, so it skips this.
# We persist NPM_CONFIG_PREFIX too so later self-updates land in the same
# place instead of hitting EACCES again.
setup_user_prefix() {
  mkdir -p "$NPM_PREFIX/lib" "$NPM_PREFIX/bin"
  export NPM_CONFIG_PREFIX="$NPM_PREFIX"
  export PATH="$NPM_PREFIX/bin:$PATH"
  persist_path_line "export NPM_CONFIG_PREFIX=\"\$HOME/.npm-global\"" \
                    "alvin-bot npm prefix"
}

# ─── Install ───────────────────────────────────────────────

# npm, quietly: no funding/audit banners, no "new major version" notice, no
# deprecation warnings from deep dependencies — all of that goes to the log.
npm_install_global() {
  env PUPPETEER_SKIP_DOWNLOAD=1 PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true \
      npm_config_update_notifier=false npm_config_fund=false npm_config_audit=false \
      "$@" npm install -g "$PKG_SPEC" --no-fund --no-audit --loglevel=error
}

install_bot() {
  step_begin 3 "$(say "Installing alvin-bot" "alvin-bot installieren")"
  local label="npm"
  [ "$PKG_SPEC" = "alvin-bot" ] || label="${PKG_SPEC##*/}"
  if [ "${USED_PORTABLE_NODE:-0}" = "1" ]; then
    # Portable runtime: pin the global prefix to the runtime dir so a stray
    # user ~/.npmrc (`prefix=…`) can't redirect the package somewhere else.
    # Install location == launcher target == self-update target, all under
    # ~/.alvin-bot/runtime. No sudo needed.
    run_logged "$label" npm_install_global NPM_CONFIG_PREFIX="$RUNTIME_DIR" \
      || step_fail "$(say "npm install -g alvin-bot failed." "npm install -g alvin-bot ist fehlgeschlagen.")"
    BIN_DIR="$RUNTIME_DIR/bin"
  else
    # System Node: try the user's existing global prefix first. Only if
    # that fails on permissions do we fall back to a user-owned prefix —
    # never sudo, so we don't scribble into system dirs.
    if ! run_logged "$label" npm_install_global; then
      printf '\n# retrying in a user-owned prefix (%s)\n' "$NPM_PREFIX" >> "$LOG_FILE"
      setup_user_prefix
      run_logged "$label" npm_install_global \
        || step_fail "$(say "npm install -g alvin-bot failed, also in a user-owned prefix." \
                            "npm install -g alvin-bot ist fehlgeschlagen, auch im eigenen Ordner.")"
    fi
    BIN_DIR="$(npm prefix -g 2>>"$LOG_FILE")/bin"
  fi

  ALVIN_BIN="$BIN_DIR/alvin-bot"
  # `|| true`: under set -e a failing cd inside the assignment would end the
  # script silently — the check below names the missing file instead.
  CLI_JS="$(cd "$BIN_DIR/../lib/node_modules/alvin-bot/bin" 2>/dev/null && pwd)/cli.js" || true
  [ -e "$ALVIN_BIN" ] && [ -f "$CLI_JS" ] \
    || step_fail "$(say "alvin-bot was installed, but $ALVIN_BIN is missing." \
                        "alvin-bot wurde installiert, aber $ALVIN_BIN fehlt.")"
  BOT_VERSION="$("$NODE_BIN" "$CLI_JS" version 2>>"$LOG_FILE" | head -1 | sed 's/^Alvin Bot //')" || true
  step_end "${BOT_VERSION:-alvin-bot}"
}

# ─── Command & PATH ────────────────────────────────────────

# The launcher for the bundled runtime. Absolute paths, so it also works
# where HOME differs (sudo, launchd). Node order: the runtime's own Node,
# then a Node 22+ on PATH, then a runtime/current layout. npm never owns
# this file (it is not in npm's bin dir), so `alvin-bot update`, `/update`
# and `npm install -g` cannot replace or break it.
write_starter() {
  local rt cli tmp
  rt="$(shell_quote "$RUNTIME_DIR")"
  cli="$(shell_quote "$RUNTIME_DIR/lib/node_modules/alvin-bot/bin/cli.js")"
  if [ -e "$STARTER" ] && ! grep -qF "$STARTER_MARK" "$STARTER" 2>/dev/null; then
    return 2   # someone else's file — leave it alone
  fi
  mkdir -p "${STARTER%/*}" || return 1
  tmp="$STARTER.tmp.$$"
  cat > "$tmp" <<EOF || return 1
#!/bin/sh
$STARTER_MARK — running the installer again repairs it.
cli=$cli
if [ ! -f "\$cli" ]; then
  echo "alvin-bot: not installed in $RUNTIME_DIR. Run the installer again:" >&2
  echo "  curl -fsSL https://unpkg.com/alvin-bot/install.sh | bash" >&2
  exit 127
fi
if [ -x $rt/bin/node ]; then exec $rt/bin/node "\$cli" "\$@"; fi
for n in "\$(command -v node 2>/dev/null)" $rt/current/bin/node; do
  [ -n "\$n" ] && [ -x "\$n" ] && [ ! -d "\$n" ] || continue
  "\$n" -e 'process.exit(+process.versions.node.split(".")[0] < 22 ? 1 : 0)' 2>/dev/null || continue
  exec "\$n" "\$cli" "\$@"
done
echo "alvin-bot: Node.js 22 or newer not found. Run the installer again:" >&2
echo "  curl -fsSL https://unpkg.com/alvin-bot/install.sh | bash" >&2
exit 127
EOF
  chmod 755 "$tmp" && mv -f "$tmp" "$STARTER"
}

# Make `alvin-bot` work: in every new terminal via PATH, and right now by
# absolute path — also where `node` is NOT on PATH (a fresh terminal before
# the profile is reloaded, launchd, cron). Checked here with a bare PATH.
setup_command() {
  step_begin 4 "$(say "Setting up the alvin-bot command" "Befehl alvin-bot einrichten")"
  SETUP_CMD="$(shell_quote "$NODE_BIN") $(shell_quote "$CLI_JS") setup"
  if [ "${USED_PORTABLE_NODE:-0}" = 1 ]; then
    # Only the launcher dir goes in front; the runtime's node/npm/npx go to
    # the END, so a Node the user installs later (brew, nvm) still wins.
    case ":$PATH_AT_START:" in
      *":${STARTER%/*}:"*) ;;
      *)
        persist_path_line "export PATH=\"\$HOME/.alvin-bot/bin:\$PATH:\$HOME/.alvin-bot/runtime/bin\"" "alvin-bot command"
        persist_fish_path "${STARTER%/*}" "$RUNTIME_DIR/bin"
        NEEDS_RELOAD=1
        ;;
    esac
    local src=0
    write_starter || src=$?
    if [ "$src" = 0 ] && env -i HOME="$HOME" PATH="/usr/bin:/bin" "$STARTER" version >>"$LOG_FILE" 2>&1; then
      SETUP_CMD="$(shell_quote "$STARTER") setup"
    elif [ "$src" = 2 ]; then
      warn "$(say "$STARTER was not written by this installer, left unchanged — using the runtime directly." \
                  "$STARTER stammt nicht von diesem Installer und bleibt unverändert — es geht direkt über die Laufzeit.")"
    else
      warn "$(say "Could not write the launcher $STARTER — using the runtime directly." \
                  "Starter $STARTER ließ sich nicht schreiben — es geht direkt über die Laufzeit.")"
    fi
  else
    case ":$PATH_AT_START:" in
      *":$BIN_DIR:"*) ;;  # already on the user's PATH
      *)
        if [ "$BIN_DIR" = "$NPM_PREFIX/bin" ]; then
          persist_path_line "export PATH=\"\$HOME/.npm-global/bin:\$PATH\"" "alvin-bot npm global bin"
        else
          persist_path_line "export PATH=\"$BIN_DIR:\$PATH\"" "alvin-bot bin"
        fi
        persist_fish_path "$BIN_DIR"
        NEEDS_RELOAD=1
        ;;
    esac
    if env PATH="$PATH_AT_START" "$ALVIN_BIN" version >>"$LOG_FILE" 2>&1; then
      SETUP_CMD="$(shell_quote "$ALVIN_BIN") setup"
    fi
  fi

  if [ -n "$RC_FILES" ]; then
    step_end "PATH → $(pretty_list "$RC_FILES")"
  else
    step_end "$(say "already on PATH" "bereits im PATH")"
  fi
  if [ -n "$RC_SKIPPED" ]; then
    warn "$(say "Not writable, left unchanged: $(pretty_list "$RC_SKIPPED")" \
                "Nicht beschreibbar, unverändert gelassen: $(pretty_list "$RC_SKIPPED")")"
  fi
}

# ─── Setup wizard ──────────────────────────────────────────

# A terminal we can ask, even under `curl … | bash` (stdin is the script
# then, but /dev/tty is still the keyboard). No terminal (CI, cron,
# `ssh host 'curl … | bash'`) → no question. Sets TTY_DEV. Never call it
# inside $(…): there stdout is a pipe and `-t 1` is always false.
find_tty() {
  TTY_DEV=''
  if [ -n "${ALVIN_INSTALL_TTY:-}" ]; then
    [ -r "$ALVIN_INSTALL_TTY" ] || return 1
    TTY_DEV="$ALVIN_INSTALL_TTY"
    return 0
  fi
  [ -t 1 ] || return 1
  # Opening /dev/tty fails without a controlling terminal, even though the
  # device node exists — so try it rather than test -r.
  ( exec 3</dev/tty ) 2>/dev/null || return 1
  TTY_DEV=/dev/tty
}

# Enter = yes; Ctrl-D (end of input) = no; Ctrl-C = no as well — the install
# is complete at this point, so it is not "cancelled". bash 3.2 (macOS)
# resumes `read` after a trap, so the handler finishes the "no" path itself.
on_ask_int() {
  trap - INT TERM
  printf '\n'
  print_later_hint
  print_reload_hint
  echo ""
  exit 0
}
ask_setup_now() {
  local tty="$1" answer='' rc=0
  printf '\n  %s %s ' "${BOLD}$(say "Set up now?" "Jetzt einrichten?")${NC}" "$(say "[Y/n]" "[J/n]")"
  trap on_ask_int INT
  IFS= read -r answer < "$tty" || rc=$?
  trap on_abort INT TERM
  if [ "$rc" != 0 ] && [ -z "$answer" ]; then
    printf '\n'
    return 1
  fi
  [ -t 1 ] || printf '%s\n' "$answer"   # echo the answer into logs/pipes
  case "$(printf '%s' "$answer" | tr '[:upper:]' '[:lower:]')" in
    ''|y|yes|j|ja) return 0 ;;
    *) return 1 ;;
  esac
}

print_later_hint() {
  echo ""
  printf '  %s\n' "$(say "Set up whenever you're ready — this works right away, in this terminal too:" \
                          "Einrichten, wann du willst — das funktioniert sofort, auch in diesem Terminal:")"
  printf '    %s\n' "${BOLD}${SETUP_CMD}${NC}"
}

print_reload_hint() {
  [ "${NEEDS_RELOAD:-0}" = 1 ] || return 0
  echo ""
  printf '  %s\n' "$(say "The short command ${BOLD}alvin-bot${NC} works in every new terminal. In this one, first run:" \
                          "Der kurze Befehl ${BOLD}alvin-bot${NC} geht in jedem neuen Terminal. In diesem vorher:")"
  if [ -n "${SHELL:-}" ]; then
    printf '    %s\n' "${BOLD}exec \$SHELL -l${NC}"
  else
    printf '    %s\n' "${BOLD}exec $(login_shell) -l${NC}"
  fi
}

# ─── Main ──────────────────────────────────────────────────

main() {
  setup_colors
  detect_lang
  PATH_AT_START="$PATH"
  NEEDS_RELOAD=0

  # Everything below lives in $HOME/.alvin-bot — refuse a missing or root HOME.
  case "${HOME:-}" in
    ''|/) fail "$(say "HOME is not set (or is /). Run the installer as a normal user." \
                      "HOME ist nicht gesetzt (oder /). Den Installer als normaler Benutzer starten.")" ;;
  esac
  [ "$RUNTIME_DIR" = "$HOME/.alvin-bot/runtime" ] || fail "unexpected runtime dir: $RUNTIME_DIR"

  # A tarball given by a relative path must survive the cd below.
  PKG_SPEC="alvin-bot"
  if [ -n "${ALVIN_INSTALL_TARBALL:-}" ]; then
    if [ -f "$ALVIN_INSTALL_TARBALL" ]; then
      PKG_SPEC="$(cd "$(dirname "$ALVIN_INSTALL_TARBALL")" && pwd)/$(basename "$ALVIN_INSTALL_TARBALL")"
    else
      PKG_SPEC="$ALVIN_INSTALL_TARBALL"
    fi
  fi

  # Run from $HOME so a stray ./.npmrc in the caller's working directory
  # (e.g. one pinning `prefix=`) isn't read as npm "project config" — npm
  # rejects a project-level prefix and prints a confusing error otherwise.
  cd "$HOME" 2>/dev/null || true
  start_log
  trap on_abort INT TERM
  trap remove_stage EXIT

  echo ""
  printf '  %s\n' "${BOLD}🦊 Alvin Bot — $(say "Installer" "Installation")${NC}"
  printf '  %s\n\n' "${DIM}─────────────────────────────────────${NC}"
  # A leftover export from testing must not install something else silently.
  [ "$PKG_SPEC" = "alvin-bot" ] || warn "$(say "Test package: $PKG_SPEC (ALVIN_INSTALL_TARBALL)" "Testpaket: $PKG_SPEC (ALVIN_INSTALL_TARBALL)")"

  step_begin 1 "$(say "Checking the system" "System prüfen")"
  detect_platform
  step_end "$OS ($NARCH)"

  ensure_node
  install_bot
  setup_command

  echo ""
  printf '  %s\n' "${GREEN}${BOLD}🎉 $(say "Alvin Bot ${BOT_VERSION:-} is installed." "Alvin Bot ${BOT_VERSION:-} ist installiert.")${NC}"

  local tty
  if find_tty; then
    tty="$TTY_DEV"
    if ask_setup_now "$tty"; then
      echo ""
      # Ctrl-C in the wizard ends the wizard, not this script: a handler
      # (not "ignore", which the child would inherit) lets the hints below
      # still appear.
      trap ':' INT
      # The runtime by absolute path, with the keyboard as stdin (ours is the
      # piped script) and the PATH of the user's shell — so the wizard's
      # summary names a command that works in THIS terminal.
      if ! env PATH="$PATH_AT_START" "$NODE_BIN" "$CLI_JS" setup < "$tty"; then
        echo ""
        warn "$(say "The setup wizard did not finish." "Der Einrichtungsassistent wurde nicht abgeschlossen.")"
      fi
      trap on_abort INT
      # Nothing saved (cancelled, terms declined, error): say how to resume.
      [ -s "${ALVIN_DATA_DIR:-$HOME/.alvin-bot}/.env" ] || print_later_hint
      print_reload_hint
      echo ""
      return 0
    fi
  fi

  print_later_hint
  print_reload_hint
  echo ""
}

# Allow sourcing for tests without running main().
if [[ "${BASH_SOURCE[0]:-$0}" == "${0}" ]]; then
  main "$@"
fi
