#!/bin/sh
# Installs jackherd for Claude Code: Bun only if it is missing, then the kit, then its setup wizard.
#
#   curl -fsSL https://unpkg.com/jackherd/install.sh | sh
#
# Never as root, no edits to shell files: the official Bun installer puts Bun into ~/.bun and says
# itself which shell file it changed. Every action is announced on one line before it runs.
set -eu

# The default is the version this file ships with. The release bump changes it together with
# package.json; install.test.ts fails while the two differ. Overridable, but only by a plain release.
JACKHERD_VERSION="${JACKHERD_VERSION:-1.13.0}"

JACKHERD_PACKAGE='jackherd'
# Test seam: the terminal the wizard asks its questions on.
JACKHERD_TEST_TTY="${JACKHERD_TEST_TTY:-/dev/tty}"
BUN_INSTALLER_URL='https://bun.com/install'
BUN_MIN_MAJOR=1
BUN_MIN_MINOR=3

say() {
  printf 'jackherd install: %s\n' "$1"
}

fail() {
  printf 'jackherd install: %s\n' "$1" >&2
  exit 1
}

# Digits and exactly two inner dots: major.minor.patch, nothing a shell or npm could read differently.
is_release() {
  case $1 in
    '' | *[!0-9.]* | .* | *. | *..* | *.*.*.*) return 1 ;;
    *.*.*) return 0 ;;
    *) return 1 ;;
  esac
}

is_number() {
  case $1 in
    '' | *[!0-9]*) return 1 ;;
    *) return 0 ;;
  esac
}

check_platform() {
  os=$(uname -s)
  case $os in
    Linux | Darwin) ;;
    *) fail "unsupported system '$os': this installer runs on Linux and macOS only" ;;
  esac
}

bun_bin_dir() {
  printf '%s/bin\n' "${BUN_INSTALL:-$HOME/.bun}"
}

# The bun on PATH, else the one the official installer leaves in ~/.bun/bin; empty when there is none.
find_bun() {
  if command -v bun >/dev/null 2>&1; then
    command -v bun
  elif [ -x "$(bun_bin_dir)/bun" ]; then
    printf '%s\n' "$(bun_bin_dir)/bun"
  fi
}

require_bun_installer_tools() {
  missing=''
  for tool in curl unzip bash; do
    command -v "$tool" >/dev/null 2>&1 || missing="$missing $tool"
  done
  [ -z "$missing" ] || fail "Bun is missing, and installing it needs:$missing. Install them and run this again."
}

install_bun() {
  require_bun_installer_tools
  installer=$(mktemp) || fail "could not create a temporary file"
  trap 'rm -f "$installer"' EXIT
  # A trapped signal would otherwise let the script carry on; exiting runs the EXIT trap above.
  trap 'exit 1' INT TERM HUP
  say "Bun not found, downloading the official installer from $BUN_INSTALLER_URL"
  curl --proto '=https' --tlsv1.2 -fsSL "$BUN_INSTALLER_URL" -o "$installer" || fail "could not download $BUN_INSTALLER_URL"
  say "running the Bun installer (installs into $(bun_bin_dir), without root)"
  bash "$installer" || fail "the Bun installer failed"
  [ -x "$(bun_bin_dir)/bun" ] || fail "the Bun installer finished, but $(bun_bin_dir)/bun is missing"
}

check_bun_version() {
  version=$("$1" --version) || fail "could not run '$1 --version'"
  major=${version%%.*}
  rest=${version#*.}
  minor=${rest%%.*}
  if ! is_number "$major" || ! is_number "$minor"; then
    fail "could not read the Bun version '$version'"
  fi
  if [ "$major" -lt "$BUN_MIN_MAJOR" ] || { [ "$major" -eq "$BUN_MIN_MAJOR" ] && [ "$minor" -lt "$BUN_MIN_MINOR" ]; }; then
    fail "Bun $version is too old, jackherd needs $BUN_MIN_MAJOR.$BUN_MIN_MINOR or newer. Update it with 'bun upgrade' and run this again."
  fi
  say "using Bun $version ($1)"
}

# Bun's global bin, not whatever jh comes first on PATH: an older install elsewhere stays untouched.
jh_bin() {
  global_bin=$("$1" pm bin -g) || fail "could not read Bun's global bin ('bun pm bin -g')"
  [ -x "$global_bin/jh" ] || fail "jh is not in Bun's global bin ($global_bin) after the install"
  printf '%s\n' "$global_bin/jh"
}

# Opening it is the test: under 'curl | sh' stdin is the script, and /dev/tty may exist without a terminal.
terminal_available() {
  (: <"$JACKHERD_TEST_TTY") 2>/dev/null
}

run_setup() {
  if terminal_available; then
    say "starting the setup: jh init --global"
    "$1" init --global <"$JACKHERD_TEST_TTY" || fail "jh init --global failed"
  else
    say "no terminal to ask questions on, setting up with the defaults: jh init --global --yes"
    "$1" init --global --yes </dev/null || fail "jh init --global --yes failed"
  fi
}

main() {
  [ "$(id -u)" -ne 0 ] || fail "run this as your own user, not as root (no sudo)"
  is_release "$JACKHERD_VERSION" || fail "JACKHERD_VERSION must be a plain release like 1.2.3, not '$JACKHERD_VERSION'"
  [ -n "${HOME:-}" ] || fail "HOME is not set"
  check_platform
  # Bun reads bunfig.toml (registry, preload, global bin) from the working directory; one in the
  # directory this was started from must not steer the install. 'init --global' writes to ~ only.
  cd "$HOME" || fail "could not change into HOME ($HOME)"

  bun=$(find_bun)
  if [ -z "$bun" ]; then
    install_bun
    bun="$(bun_bin_dir)/bun"
  fi
  case $bun in
    /*) ;;
    *) fail "found bun at '$bun', expected an absolute path" ;;
  esac
  check_bun_version "$bun"
  # This run only: the kit's CLI starts with '#!/usr/bin/env bun'.
  PATH="$(dirname "$bun"):$PATH"
  export PATH

  spec="$JACKHERD_PACKAGE@$JACKHERD_VERSION"
  say "installing $spec: bun add -g --ignore-scripts $spec"
  "$bun" add -g --ignore-scripts "$spec" || fail "bun add -g failed"

  # An assignment, so a failure inside the substitution stops the run (set -e) instead of passing on ''.
  jh=$(jh_bin "$bun")
  run_setup "$jh"
  say "done"
}

main
