#!/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.16.0}"

JACKHERD_PACKAGE='jackherd'
# Test seam: the terminal the wizard asks its questions on.
JACKHERD_TEST_TTY="${JACKHERD_TEST_TTY:-/dev/tty}"
# Test seam: a packed tarball (absolute path) installed instead of the published package, so CI can prove a build
# before it is released. Unset in every real run.
JACKHERD_TEST_PACKAGE="${JACKHERD_TEST_PACKAGE:-}"
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 first executable bun along PATH, spelled the way PATH names it. Walked here and not asked of
# 'command -v', which some shells (bash 3.2 as sh on macOS) answer with an absolute path even for a
# relative entry, so the check for a relative one in main would never fire. An empty entry means the
# current directory and counts as relative.
bun_on_path() {
  rest="$PATH:"
  while [ -n "$rest" ]; do
    entry=${rest%%:*}
    rest=${rest#*:}
    [ -n "$entry" ] || entry=.
    if [ -f "$entry/bun" ] && [ -x "$entry/bun" ]; then
      printf '%s/bun\n' "$entry"
      return 0
    fi
  done
  return 1
}

# The bun on PATH, else the one the official installer leaves in ~/.bun/bin; empty when there is none.
find_bun() {
  found=$(bun_on_path) || found=''
  if [ -n "$found" ]; then
    printf '%s\n' "$found"
  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
}

# The controlling terminal's own device node, else the path as given. macOS kqueue, which Bun reads stdin through,
# rejects /dev/tty with EINVAL but accepts the real device (/dev/ttys003). On macOS 'tty </dev/tty' prints
# /dev/tty itself, so the device comes from 'tty' on the inherited stdin when that is a terminal, else from the
# shell's own TTY column of 'ps' (ttys003 on macOS, pts/3 on Linux; ? or ?? when there is none).
terminal_device() {
  device=$(tty 2>/dev/null) || device=''
  if [ "$device" = /dev/tty ] || [ ! -c "$device" ]; then
    name=$(ps -o tty= -p $$ 2>/dev/null) || name=''
    # shellcheck disable=SC2086 # word splitting trims the padding ps puts around the column
    set -- $name
    case ${1:-} in
      '' | '?' | '??') device='' ;;
      *) device="/dev/$1" ;;
    esac
  fi
  if [ -c "$device" ] && [ "$device" != /dev/tty ]; then
    printf '%s\n' "$device"
  else
    printf '%s\n' "$JACKHERD_TEST_TTY"
  fi
}

run_setup() {
  if terminal_available; then
    say "starting the setup: jh init --global"
    "$1" init --global <"$(terminal_device)" || 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"
  [ -z "$JACKHERD_TEST_PACKAGE" ] || spec="$JACKHERD_TEST_PACKAGE"
  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
