#!/bin/sh
# Jarvis installer for macOS and Linux.
#
#   curl -fsSL https://jarvis.yigito.com/install.sh | sh
#   curl -fsSL https://jarvis.yigito.com/install.sh | sh -s -- --yes --no-onboard
#
# What it does, in order:
#   1. checks Node.js >= 20, git and npm (prints the exact fix if one is missing)
#   2. clones or updates Jarvis into ~/.jarvis/app (git, at a ref you choose)
#   3. installs dependencies and builds the daemon and the phone app
#   4. writes a `jarvis` launcher into ~/.local/bin
#   5. runs `jarvis setup`, which asks a few questions and configures the rest
#
# It never uses sudo, never runs as root, and never installs system packages
# without asking. Re-running it upgrades in place. Remove with --uninstall.
#
# Options (or environment variables):
#   -y, --yes        take defaults, ask nothing          JARVIS_YES=1
#   --no-onboard     stop after installing; skip `jarvis setup`
#   --ref <ref>      branch, tag or commit to install     JARVIS_REF   (default: main)
#   --dir <path>     where the code goes                  JARVIS_DIR   (default: ~/.jarvis/app)
#   --uninstall      remove the code and the launcher (asks before touching your config)
#                    JARVIS_REPO overrides the git URL; JARVIS_BIN_DIR the launcher dir.
#
# The whole script is wrapped in main(), called on the last line, so a
# partial download runs nothing.

set -eu

main() {
  JARVIS_REPO="${JARVIS_REPO:-https://github.com/yigitoo/claude-jarvis.git}"
  JARVIS_REF="${JARVIS_REF:-main}"
  JARVIS_DIR="${JARVIS_DIR:-$HOME/.jarvis/app}"
  JARVIS_BIN_DIR="${JARVIS_BIN_DIR:-$HOME/.local/bin}"
  JARVIS_CONFIG_DIR="${JARVIS_HOME:-$HOME/.jarvis}"
  YES="${JARVIS_YES:-0}"
  ONBOARD=1
  UNINSTALL=0

  while [ $# -gt 0 ]; do
    case "$1" in
      -y|--yes) YES=1 ;;
      --no-onboard) ONBOARD=0 ;;
      --uninstall) UNINSTALL=1 ;;
      --ref) [ $# -ge 2 ] || die "--ref needs a branch, tag or commit"; JARVIS_REF="$2"; shift ;;
      --ref=*) JARVIS_REF="${1#--ref=}" ;;
      --dir) [ $# -ge 2 ] || die "--dir needs a path"; JARVIS_DIR="$2"; shift ;;
      --dir=*) JARVIS_DIR="${1#--dir=}" ;;
      -h|--help) usage; return 0 ;;
      *) die "unknown option: $1 (try --help)" ;;
    esac
    shift
  done
  case "$YES" in 1|true|yes) YES=1 ;; *) YES=0 ;; esac
  case "$JARVIS_DIR" in "~"/*) JARVIS_DIR="$HOME/${JARVIS_DIR#"~/"}" ;; esac
  case "$JARVIS_DIR" in /*) ;; *) JARVIS_DIR="$(pwd)/$JARVIS_DIR" ;; esac

  setup_style
  setup_tty

  if [ "$(id -u)" = 0 ] && [ "${JARVIS_ALLOW_ROOT:-0}" != 1 ]; then
    die "Do not run this as root. Jarvis runs as your own user. (Set JARVIS_ALLOW_ROOT=1 to override, e.g. in a throwaway container.)"
  fi

  detect_platform

  if [ "$UNINSTALL" = 1 ]; then
    uninstall
    return 0
  fi

  say "${BOLD}Jarvis installer${RESET}"
  ok "$OS_LABEL $ARCH"
  check_prereqs
  fetch_code
  install_deps
  build
  write_shim
  path_hint

  if [ "$ONBOARD" = 0 ]; then
    say ""
    say "Installed. Next: ${BOLD}jarvis setup${RESET}"
    return 0
  fi
  say ""
  say "Starting ${BOLD}jarvis setup${RESET}..."
  export JARVIS_LAUNCHER="$SHIM"
  if [ "$YES" = 1 ] || [ "$INTERACTIVE" = 0 ]; then
    exec "$SHIM" setup --yes
  fi
  exec "$SHIM" setup </dev/tty
}

usage() {
  cat <<'USAGE'
Jarvis installer for macOS and Linux

  curl -fsSL https://jarvis.yigito.com/install.sh | sh -s -- [options]

  -y, --yes        take defaults, ask nothing (JARVIS_YES=1)
  --no-onboard     install only; skip `jarvis setup`
  --ref <ref>      branch, tag or commit (JARVIS_REF, default: main)
  --dir <path>     install location (JARVIS_DIR, default: ~/.jarvis/app)
  --uninstall      remove the code and launcher; asks before removing ~/.jarvis

  JARVIS_REPO      git URL or local path to install from
  JARVIS_BIN_DIR   where the jarvis launcher goes (default: ~/.local/bin)
USAGE
}

# ---------- output ----------

setup_style() {
  BOLD="" DIM="" RED="" GREEN="" YELLOW="" RESET=""
  if [ -t 1 ] && [ -z "${NO_COLOR+x}" ] && [ "${TERM:-}" != dumb ]; then
    ESC="$(printf '\033')"
    BOLD="${ESC}[1m" DIM="${ESC}[2m" RED="${ESC}[31m" GREEN="${ESC}[32m" YELLOW="${ESC}[33m" RESET="${ESC}[0m"
  fi
  case "${LC_ALL:-${LC_CTYPE:-${LANG:-}}}" in
    *UTF-8*|*utf-8*|*UTF8*|*utf8*) M_OK="✓" M_WARN="!" M_FAIL="✗" M_DOT="·" ;;
    *) M_OK="ok" M_WARN="!!" M_FAIL="xx" M_DOT="-" ;;
  esac
}

say() { printf '%s\n' "$*"; }
ok() { printf '  %s%s%s %s\n' "$GREEN" "$M_OK" "$RESET" "$*"; }
warn() { printf '  %s%s%s %s\n' "$YELLOW" "$M_WARN" "$RESET" "$*"; }
fail() { printf '  %s%s%s %s\n' "$RED" "$M_FAIL" "$RESET" "$*" >&2; }
note() { printf '    %s%s%s\n' "$DIM" "$*" "$RESET"; }
step() { printf '  %s%s%s %s\n' "$DIM" "$M_DOT" "$RESET" "$*"; }
die() { fail "$*"; exit 1; }

# Questions are read from /dev/tty so they work under `curl | sh`.
setup_tty() {
  INTERACTIVE=0
  if [ "$YES" = 0 ] && [ -t 1 ] && (: </dev/tty) 2>/dev/null; then INTERACTIVE=1; fi
}

# ask_yn "Question" default(y|n) -> returns 0 for yes
ask_yn() {
  if [ "$INTERACTIVE" = 0 ]; then
    [ "$2" = y ]
    return
  fi
  if [ "$2" = y ]; then hint="[Y/n]"; else hint="[y/N]"; fi
  while :; do
    printf '? %s %s ' "$1" "$hint" >/dev/tty
    IFS= read -r answer </dev/tty || answer=""
    case "$answer" in
      "") [ "$2" = y ]; return ;;
      y|Y|yes|YES|e|E|evet) return 0 ;;
      n|N|no|NO|h|H|hayir) return 1 ;;
      *) printf '  Answer y or n.\n' >/dev/tty ;;
    esac
  done
}

# Display only: shows $HOME as a literal "~".
# shellcheck disable=SC2088
tilde() {
  case "$1" in "$HOME") printf '~' ;; "$HOME"/*) printf '~/%s' "${1#"$HOME"/}" ;; *) printf '%s' "$1" ;; esac
}

now() { date +%s; }

# run_logged "doing" "done" cmd... : one line on success, the log tail on failure.
run_logged() {
  label="$1"
  done_label="$2"
  shift 2
  step "$label..."
  t0="$(now)"
  if "$@" >>"$LOG" 2>&1; then
    ok "$done_label ($(($(now) - t0))s)"
  else
    fail "$label failed. Last lines of $(tilde "$LOG"):"
    tail -n 25 "$LOG" | sed 's/^/      /' >&2
    exit 1
  fi
}

# ---------- platform and prerequisites ----------

detect_platform() {
  ARCH="$(uname -m)"
  case "$(uname -s)" in
    Darwin) OS=macos OS_LABEL=macOS ;;
    Linux)
      OS=linux OS_LABEL=Linux
      if grep -qi microsoft /proc/version 2>/dev/null; then OS_LABEL="Linux (WSL)"; fi
      ;;
    MINGW*|MSYS*|CYGWIN*) die "This is the macOS/Linux installer. On Windows use WSL 2 (recommended) or: irm https://jarvis.yigito.com/install.ps1 | iex" ;;
    *) die "Unsupported system: $(uname -s). Jarvis supports macOS and Linux (Windows via WSL 2)." ;;
  esac
  PM=""
  if [ "$OS" = macos ]; then
    if command -v brew >/dev/null 2>&1; then PM=brew; fi
  else
    for p in apt-get dnf pacman zypper apk brew; do
      if command -v "$p" >/dev/null 2>&1; then PM="$p"; break; fi
    done
  fi
}

# The install command for a package on this system (printed, or offered when it needs no sudo).
fix_for() {
  case "$1:$PM" in
    node:brew) echo "brew install node" ;;
    node:apt-get) echo "sudo apt-get install -y nodejs npm   # if that is older than 20: https://nodejs.org/en/download" ;;
    node:dnf) echo "sudo dnf install -y nodejs npm" ;;
    node:pacman) echo "sudo pacman -S nodejs npm" ;;
    node:zypper) echo "sudo zypper install nodejs20" ;;
    node:apk) echo "sudo apk add nodejs npm" ;;
    node:*) echo "install Node.js 20 or newer from https://nodejs.org/en/download" ;;
    git:brew) echo "brew install git" ;;
    git:apt-get) echo "sudo apt-get install -y git" ;;
    git:dnf) echo "sudo dnf install -y git" ;;
    git:pacman) echo "sudo pacman -S git" ;;
    git:zypper) echo "sudo zypper install git" ;;
    git:apk) echo "sudo apk add git" ;;
    git:*) if [ "$OS" = macos ]; then echo "xcode-select --install"; else echo "install git with your package manager"; fi ;;
    tailscale:brew) echo "brew install --cask tailscale" ;;
    tailscale:*) if [ "$OS" = macos ]; then echo "install from https://tailscale.com/download/mac"; else echo "curl -fsSL https://tailscale.com/install.sh | sh"; fi ;;
    whisper:brew) echo "brew install whisper-cpp" ;;
    whisper:*) echo "build whisper.cpp (https://github.com/ggml-org/whisper.cpp) and put whisper-server on PATH" ;;
    claude:*) echo "curl -fsSL https://claude.ai/install.sh | bash   # then run: claude" ;;
  esac
}

# Offer to run a fix only when interactive, only for brew (no sudo), default no.
offer_fix() {
  fix="$(fix_for "$1")"
  note "Fix: $fix"
  case "$fix" in
    "brew install "*)
      if ask_yn "Run \`$fix\` now?" n; then
        # shellcheck disable=SC2086 # fix is one of our fixed brew commands above
        brew ${fix#brew } || true
        return 0
      fi
      ;;
  esac
  return 1
}

node_ok() { command -v node >/dev/null 2>&1 && node -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 20 ? 0 : 1)' 2>/dev/null; }

check_prereqs() {
  missing=""
  if node_ok; then
    ok "Node.js $(node -p process.versions.node)"
  else
    if command -v node >/dev/null 2>&1; then fail "Node.js $(node -p process.versions.node 2>/dev/null) is too old; Jarvis needs 20 or newer"; else fail "Node.js not found; Jarvis needs 20 or newer"; fi
    if offer_fix node && node_ok; then ok "Node.js $(node -p process.versions.node)"; else missing="$missing node"; fi
  fi
  if command -v git >/dev/null 2>&1; then
    ok "git $(git --version | awk '{print $3}')"
  else
    fail "git not found"
    if offer_fix git && command -v git >/dev/null 2>&1; then ok "git"; else missing="$missing git"; fi
  fi
  if command -v npm >/dev/null 2>&1; then
    ok "npm $(npm --version 2>/dev/null)"
  else
    fail "npm not found (it ships with Node.js)"
    note "Fix: $(fix_for node)"
    missing="$missing npm"
  fi
  [ -z "$missing" ] || die "Missing:$missing. Install it, then run this again."

  # Optional: report, never block.
  if command -v claude >/dev/null 2>&1; then ok "Claude Code"; else warn "Claude Code CLI not found (used to sign in). $(fix_for claude)"; fi
  if command -v tailscale >/dev/null 2>&1; then ok "Tailscale"; else warn "Tailscale not found (needed for phone access): $(fix_for tailscale)"; fi
  if command -v whisper-server >/dev/null 2>&1; then ok "whisper.cpp"; else warn "whisper.cpp not found (optional, for voice): $(fix_for whisper)"; fi
}

# ---------- code ----------

fetch_code() {
  # The config dir holds secrets; create it private (the daemon checks for go-rwx).
  if [ ! -d "$JARVIS_CONFIG_DIR" ]; then (umask 077 && mkdir -p "$JARVIS_CONFIG_DIR"); fi
  mkdir -p "$(dirname "$JARVIS_DIR")"
  if [ -d "$JARVIS_DIR/.git" ]; then
    if [ -n "$(git -C "$JARVIS_DIR" status --porcelain --untracked-files=no 2>/dev/null)" ]; then
      die "$(tilde "$JARVIS_DIR") has local changes. Commit or stash them, or use --dir for a fresh copy."
    fi
    git -C "$JARVIS_DIR" remote set-url origin "$JARVIS_REPO"
    action="Updated"
  elif [ -e "$JARVIS_DIR" ] && [ -n "$(ls -A "$JARVIS_DIR" 2>/dev/null)" ]; then
    die "$(tilde "$JARVIS_DIR") exists and is not a Jarvis checkout. Move it, or pick another place with --dir."
  else
    mkdir -p "$JARVIS_DIR"
    git -C "$JARVIS_DIR" init -q
    git -C "$JARVIS_DIR" remote add origin "$JARVIS_REPO"
    action="Cloned"
  fi
  LOG="$JARVIS_DIR/.jarvis-install.log"
  : >"$LOG"
  before="$(git -C "$JARVIS_DIR" rev-parse -q --verify HEAD 2>/dev/null || true)"
  step "Fetching $JARVIS_REF..."
  if ! git -C "$JARVIS_DIR" fetch -q --depth 1 origin "$JARVIS_REF" >>"$LOG" 2>&1; then
    fail "Could not fetch $JARVIS_REF from $JARVIS_REPO."
    tail -n 5 "$LOG" | sed 's/^/      /' >&2
    exit 1
  fi
  git -C "$JARVIS_DIR" -c advice.detachedHead=false checkout -q --force --detach FETCH_HEAD
  : >"$JARVIS_DIR/.jarvis-installed"
  REV="$(git -C "$JARVIS_DIR" rev-parse --short HEAD)"
  if [ "$before" = "$(git -C "$JARVIS_DIR" rev-parse HEAD)" ]; then action="Already at"; fi
  ok "$action $JARVIS_REF ($REV) in $(tilde "$JARVIS_DIR")"
}

# Dependencies are reinstalled only when the lockfile or Node's major version changed.
install_deps() {
  stamp_file="$JARVIS_DIR/node_modules/.jarvis-deps"
  if [ -f "$JARVIS_DIR/package-lock.json" ]; then
    stamp="$(git -C "$JARVIS_DIR" rev-parse HEAD:package-lock.json) node$(node -p 'process.versions.node.split(".")[0]')"
    mode=ci
  else
    stamp="nolock $(git -C "$JARVIS_DIR" rev-parse HEAD) node$(node -p 'process.versions.node.split(".")[0]')"
    mode=install
  fi
  if [ -f "$stamp_file" ] && [ "$(cat "$stamp_file")" = "$stamp" ]; then
    ok "Dependencies up to date"
    return
  fi
  cd "$JARVIS_DIR"
  # Only what the daemon and the phone app need (not the desktop shell).
  run_logged "Installing dependencies (npm $mode)" "Installed dependencies" env ELECTRON_SKIP_BINARY_DOWNLOAD=1 npm "$mode" --no-audit --no-fund --include=dev \
    -w packages/protocol -w apps/jarvis-daemon -w apps/jarvis-app
  printf '%s\n' "$stamp" >"$stamp_file"
}

# Rebuilt only when the checked-out commit changed.
build() {
  stamp_file="$JARVIS_DIR/apps/jarvis-daemon/dist/.jarvis-build"
  head="$(git -C "$JARVIS_DIR" rev-parse HEAD)"
  if [ -f "$stamp_file" ] && [ "$(cat "$stamp_file")" = "$head" ] && [ -f "$JARVIS_DIR/apps/jarvis-app/dist/index.html" ]; then
    ok "Build up to date"
    return
  fi
  cd "$JARVIS_DIR"
  run_logged "Building the daemon" "Built the daemon" npm run build -w @superskill/jarvis-daemon
  run_logged "Building the phone app" "Built the phone app" npm run build -w @superskill/jarvis-app
  printf '%s\n' "$head" >"$stamp_file"
}

# ---------- launcher ----------

SHIM_MARK="# jarvis launcher, written by install.sh"

sq() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }

write_shim() {
  SHIM="$JARVIS_BIN_DIR/jarvis"
  entry="$JARVIS_DIR/apps/jarvis-daemon/bin/jarvis.mjs"
  mkdir -p "$JARVIS_BIN_DIR"
  if [ -e "$SHIM" ] && ! grep -q "$SHIM_MARK" "$SHIM" 2>/dev/null; then
    warn "$(tilde "$SHIM") exists and was not written by this installer; leaving it alone."
    note "Remove it (it may be an old \`npm link\`) and run this again to use the new launcher."
    SHIM="$JARVIS_BIN_DIR/.jarvis-launcher"
  fi
  tmp="$SHIM.tmp.$$"
  {
    printf '#!/bin/sh\n%s. Re-run the installer to update.\n' "$SHIM_MARK"
    printf 'entry=%s\n' "$(sq "$entry")"
    printf 'fallback_node=%s\n' "$(sq "$(command -v node)")"
    # shellcheck disable=SC2016 # these lines are written into the launcher verbatim
    printf 'if command -v node >/dev/null 2>&1; then exec node "$entry" "$@"; fi\n'
    # shellcheck disable=SC2016
    printf 'exec "$fallback_node" "$entry" "$@"\n'
  } >"$tmp"
  chmod 755 "$tmp"
  mv -f "$tmp" "$SHIM"
  ok "Launcher $(tilde "$SHIM") ($("$SHIM" --version))"
}

path_hint() {
  case ":$PATH:" in
    *":$JARVIS_BIN_DIR:"*) return ;;
  esac
  dir="$JARVIS_BIN_DIR"
  case "$dir" in "$HOME"/*) dir="\$HOME/${dir#"$HOME"/}" ;; esac
  warn "$(tilde "$JARVIS_BIN_DIR") is not on your PATH. Add it for your shell:"
  note "zsh:  echo 'export PATH=\"$dir:\$PATH\"' >> ~/.zshrc"
  note "bash: echo 'export PATH=\"$dir:\$PATH\"' >> ~/.bashrc"
  note "fish: fish_add_path $(tilde "$JARVIS_BIN_DIR")"
  note "Then open a new terminal."
}

# ---------- uninstall ----------

uninstall() {
  say "${BOLD}Jarvis uninstall${RESET}"
  shim="$JARVIS_BIN_DIR/jarvis"
  if [ -d "$JARVIS_DIR" ] && [ ! -f "$JARVIS_DIR/.jarvis-installed" ]; then
    die "$(tilde "$JARVIS_DIR") was not created by this installer; not removing it."
  fi
  case "$JARVIS_DIR" in "" | / | "$HOME" | "$HOME/") die "Refusing to remove $JARVIS_DIR" ;; esac
  if ! ask_yn "Remove $(tilde "$JARVIS_DIR") and the jarvis launcher?" y; then
    say "Nothing removed."
    return
  fi

  # Stop the login service first so it does not restart a missing launcher.
  plist="$HOME/Library/LaunchAgents/com.superskill.jarvis.plist"
  unit="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/jarvis.service"
  if [ "$OS" = macos ] && [ -f "$plist" ]; then
    launchctl bootout "gui/$(id -u)/com.superskill.jarvis" 2>/dev/null || true
    rm -f "$plist"
    ok "Removed the login service"
  elif [ "$OS" = linux ] && [ -f "$unit" ]; then
    systemctl --user disable --now jarvis >/dev/null 2>&1 || true
    rm -f "$unit"
    systemctl --user daemon-reload >/dev/null 2>&1 || true
    ok "Removed the login service"
  fi

  if [ -f "$HOME/.claude/skills/superskill/.superskill-pack" ] && [ -f "$JARVIS_DIR/install.sh" ]; then
    if ask_yn "Also remove the superskill skills from ~/.claude/skills?" n; then
      bash "$JARVIS_DIR/install.sh" --uninstall >/dev/null && ok "Removed the skill pack"
    else
      note "Kept the skill pack in ~/.claude/skills."
    fi
  fi

  for f in "$shim" "$JARVIS_BIN_DIR/.jarvis-launcher"; do
    if [ -f "$f" ] && grep -q "$SHIM_MARK" "$f" 2>/dev/null; then rm -f "$f" && ok "Removed $(tilde "$f")"; fi
  done
  if [ -d "$JARVIS_DIR" ]; then rm -rf "$JARVIS_DIR" && ok "Removed $(tilde "$JARVIS_DIR")"; fi

  if [ -d "$JARVIS_CONFIG_DIR" ]; then
    note "Your config, paired devices, brain notes and speech models are in $(tilde "$JARVIS_CONFIG_DIR")."
    if ask_yn "Remove $(tilde "$JARVIS_CONFIG_DIR") too? This cannot be undone." n; then
      rm -rf "$JARVIS_CONFIG_DIR" && ok "Removed $(tilde "$JARVIS_CONFIG_DIR")"
    else
      ok "Kept $(tilde "$JARVIS_CONFIG_DIR")"
    fi
  fi
  if command -v tailscale >/dev/null 2>&1; then note "If you ran tailscale serve for Jarvis: tailscale serve --https=443 off"; fi
  say "Jarvis is uninstalled."
}

main "$@"
