#!/bin/sh
# Commission installer (macOS and Linux): installs the hub on this machine.
#
#   curl -fsSL https://commission.sh/install | sh
#   curl -fsSL https://commission.sh/install | sh -s -- --yes
#
# What it does, as you (never sudo):
#   1. checks Claude Code and Tailscale are installed, with the fix if not;
#   2. downloads the Commission host bundle for this machine from the
#      release site (it carries its own Node; nothing else to install) and
#      checks its SHA-256, then every file in it;
#   3. unpacks it to ~/.supervisor/releases/<version> and points
#      ~/.supervisor/current at it (the same layout as remote machines);
#   4. links ~/.local/bin/commission to it (shell startup files are never edited);
#   5. runs `commission host install --publish`: the host service (a LaunchAgent,
#      or a systemd user unit) and, after you say yes, Tailscale Serve.
#
# Options: --yes (no questions: publish on the tailnet without asking),
#          --version V (default: the newest release; also COMMISSION_VERSION),
#          --profile NAME, --port N, --data-dir DIR (passed to host install),
#          --no-service (unpack and link only), --help.
# For apps driving it: COMMISSION_PROGRESS=1 prints "progress: <step> <text>"
# lines on stdout (steps: check, download, verify, unpack, link, service, done)
# and "error: <code> <text>" on failure.
#
# The release site is https://commission.sh/download (scripts/release.ts
# writes the site a release is cut for); COMMISSION_RELEASE_URL overrides it
# (e.g. a local test server).

set -eu
umask 077

RELEASE_URL_DEFAULT="https://commission.sh/download"
release_url="${COMMISSION_RELEASE_URL:-$RELEASE_URL_DEFAULT}"
version="${COMMISSION_VERSION:-}"
progress="${COMMISSION_PROGRESS:-0}"
yes=0
service=1
profile=""
port=""
data_dir=""
base="$HOME/.supervisor"
bin_dir="$HOME/.local/bin"

usage() {
  cat <<'EOF'
Usage: install.sh [--yes] [--version V] [--profile NAME] [--port N] [--data-dir DIR] [--no-service]

Installs the Commission hub on this machine as you (never sudo): checks Claude
Code and Tailscale, downloads and verifies the host bundle, unpacks it to
~/.supervisor/releases/<version>, links ~/.local/bin/commission and runs
`commission host install --publish`.

  --yes          answer yes (publish on your tailnet without asking)
  --version V    install this release instead of the newest
  --profile, --port, --data-dir
                 passed to `commission host install`
  --no-service   unpack and link only
EOF
}

say() {
  if [ "$progress" = 1 ]; then
    printf 'progress: %s %s\n' "$1" "$2"
  else
    printf '%s\n' "$2"
  fi
}

die() {
  # die <code> <message> [fix]
  if [ "$progress" = 1 ]; then
    printf 'error: %s %s\n' "$1" "$2"
    [ $# -ge 3 ] && printf 'fix: %s\n' "$3"
  else
    printf '\nCommission was not installed: %s\n' "$2" >&2
    [ $# -ge 3 ] && printf '  Fix: %s\n' "$3" >&2
  fi
  exit 1
}

warn() {
  if [ "$progress" = 1 ]; then
    printf 'warning: %s\n' "$1"
  else
    printf 'Note: %s\n' "$1" >&2
  fi
}

while [ $# -gt 0 ]; do
  case "$1" in
    --yes|-y) yes=1 ;;
    --no-service) service=0 ;;
    --version) [ $# -ge 2 ] || die usage "--version needs a value"; version="$2"; shift ;;
    --profile) [ $# -ge 2 ] || die usage "--profile needs a value"; profile="$2"; shift ;;
    --port) [ $# -ge 2 ] || die usage "--port needs a value"; port="$2"; shift ;;
    --data-dir) [ $# -ge 2 ] || die usage "--data-dir needs a value"; data_dir="$2"; shift ;;
    --help|-h) usage; exit 0 ;;
    *) die usage "unknown option $1" "run with --help to see the options" ;;
  esac
  shift
done

case "$release_url" in
  https://*.invalid|https://*.invalid/*|'')
    die no_release_site "this installer does not know where releases are published" \
      "run: curl -fsSL https://commission.sh/install | sh" ;;
  https://*|http://127.0.0.1:*|http://localhost:*) ;;
  *) die no_release_site "the release site must be an https:// URL ($release_url)" ;;
esac
release_url=${release_url%/}

safe_name() {
  case "$1" in
    ''|.*|*/*|*[!A-Za-z0-9._-]*) return 1 ;;
  esac
  return 0
}

# --- 1. This machine ---------------------------------------------------------

say check "Checking this machine…"
os=$(uname -s)
machine=$(uname -m)
case "$machine" in
  x86_64|amd64) arch=x64 ;;
  arm64|aarch64) arch=arm64 ;;
  *) die unsupported_arch "this processor ($machine) is not supported; Commission runs on x64 and arm64" ;;
esac
case "$os" in
  Darwin)
    target="darwin-$arch"
    # Under Rosetta, uname reports x86_64 on Apple silicon: use the native build.
    if [ "$arch" = x64 ] && [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = 1 ]; then
      target=darwin-arm64
    fi
    tailscale_bin=/Applications/Tailscale.app/Contents/MacOS/Tailscale
    tailscale_fix="install Tailscale from https://tailscale.com/download/mac (the App Store or standalone app), open it and log in"
    ;;
  Linux)
    glibc=$(getconf GNU_LIBC_VERSION 2>/dev/null | awk '{ print $2 }') || glibc=""
    [ -n "$glibc" ] || die unsupported_libc "this Linux does not use glibc (Alpine and other musl systems are not supported)"
    major=${glibc%%.*}
    minor=${glibc#*.}
    minor=${minor%%.*}
    if [ "$major" -lt 2 ] || { [ "$major" -eq 2 ] && [ "$minor" -lt 28 ]; }; then
      die unsupported_libc "glibc $glibc is too old; Commission needs 2.28 or newer (Debian 10, Ubuntu 18.10, RHEL 8 or later)"
    fi
    target="linux-$arch-glibc"
    tailscale_bin=""
    for c in /usr/bin/tailscale /usr/local/bin/tailscale /snap/bin/tailscale; do
      if [ -x "$c" ]; then tailscale_bin=$c; break; fi
    done
    tailscale_fix="install Tailscale with: curl -fsSL https://tailscale.com/install.sh | sh  then run: sudo tailscale up"
    ;;
  *) die unsupported_os "$os is not supported by this installer (macOS and Linux are; Windows machines are added from the hub)" ;;
esac

claude=""
for c in "$HOME/.local/bin/claude" "$HOME/.claude/local/claude" /opt/homebrew/bin/claude /usr/local/bin/claude; do
  if [ -x "$c" ] && [ ! -d "$c" ]; then claude=$c; break; fi
done
if [ -z "$claude" ]; then
  c=$(command -v claude 2>/dev/null) || c=""
  case "$c" in /*) claude=$c ;; esac
fi
[ -n "$claude" ] || die claude_missing "Claude Code is not installed" \
  "install it with: curl -fsSL https://claude.ai/install.sh | bash  then run claude once to sign in"
if "$claude" auth status --json </dev/null 2>/dev/null | tr -d ' \t\r\n' | grep -q '"loggedIn":false'; then
  die claude_auth "Claude Code is installed but not signed in" "run: claude auth login  (or start claude and use /login)"
fi

if [ -z "$tailscale_bin" ] || [ ! -x "$tailscale_bin" ]; then
  die tailscale_missing "Tailscale is not installed; your phone and other devices reach the hub over your tailnet" "$tailscale_fix"
fi

if command -v curl >/dev/null 2>&1; then
  fetch() { curl -fsSL --proto '=https,http' --retry 2 -o "$2" "$1"; }
  fetch_out() { curl -fsSL --proto '=https,http' --retry 2 "$1"; }
elif command -v wget >/dev/null 2>&1; then
  fetch() { wget -q -O "$2" "$1"; }
  fetch_out() { wget -q -O - "$1"; }
else
  die no_downloader "neither curl nor wget is installed" "install curl"
fi

if command -v sha256sum >/dev/null 2>&1; then
  sha256() { sha256sum "$1" | cut -d ' ' -f 1; }
  sha256_check() { sha256sum -c --status "$1"; }
elif command -v shasum >/dev/null 2>&1; then
  sha256() { shasum -a 256 "$1" | cut -d ' ' -f 1; }
  sha256_check() { shasum -a 256 -c --status "$1"; }
else
  die no_sha256 "no SHA-256 tool (sha256sum or shasum) was found"
fi

# --- 2. Download -------------------------------------------------------------

if [ -z "$version" ]; then
  say download "Finding the newest release…"
  index=$(fetch_out "$release_url/latest.json") || die download_failed "could not read $release_url/latest.json" "check your internet connection and try again"
  version=$(printf '%s' "$index" | tr -d '\n' | sed -n 's/^[^{]*{[^}]*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
fi
safe_name "$version" || die bad_release "the release index names no usable version"

name="supervisor-host-$version-$target"
mkdir -p "$base/incoming" "$base/releases"
chmod 700 "$base" "$base/incoming" "$base/releases"
tarball="$base/incoming/$name.tar.gz"
url="$release_url/v/$version/$name.tar.gz"

say download "Downloading Commission $version for $target…"
expected=$(fetch_out "$url.sha256" | awk '{ print $1; exit }') || expected=""
case "$expected" in
  ''|*[!0-9a-f]*) die download_failed "could not read the checksum $url.sha256" "check that release $version exists for $target" ;;
esac
[ ${#expected} -eq 64 ] || die download_failed "$url.sha256 is not a SHA-256"
fetch "$url" "$tarball.partial" || { rm -f "$tarball.partial"; die download_failed "could not download $url"; }
mv -f "$tarball.partial" "$tarball"

say verify "Checking the download…"
actual=$(sha256 "$tarball")
if [ "$actual" != "$expected" ]; then
  rm -f "$tarball"
  die checksum_mismatch "the download does not match its published SHA-256 (nothing was installed)" "try again; if it keeps happening, tell the release owner"
fi

# --- 3. Unpack (remote-script.ts `activate`) ---------------------------------

release="$base/releases/$version"
if [ -d "$release" ] && [ -x "$release/node/bin/node" ]; then
  say unpack "Commission $version is already unpacked."
else
  say unpack "Unpacking…"
  rm -rf "$release"
  tmp=$(mktemp -d "$base/releases/.unpack.XXXXXX") || die unpack_failed "could not create a directory in $base/releases"
  if ! tar -xzf "$tarball" -C "$tmp" 2>/dev/null; then
    rm -rf "$tmp" "$tarball"
    die unpack_failed "the download could not be unpacked"
  fi
  root="$tmp/$name"
  if [ ! -f "$root/SHA256SUMS" ] || ! (cd "$root" && sha256_check SHA256SUMS); then
    rm -rf "$tmp" "$tarball"
    die checksum_mismatch "a file in the bundle does not match its checksum (nothing was installed)"
  fi
  mv "$root" "$release" || die unpack_failed "could not move the release into $release"
  rm -rf "$tmp"
fi
rm -f "$tarball"

rm -f "$base/.current.tmp"
ln -s "releases/$version" "$base/.current.tmp"
"$release/node/bin/node" -e 'require("fs").renameSync(process.argv[1], process.argv[2])' \
  "$base/.current.tmp" "$base/current" || {
  rm -f "$base/.current.tmp"
  die switch_failed "could not switch $base/current to $version"
}

# --- 4. The commission command ----------------------------------------------

say link "Linking $bin_dir/commission…"
mkdir -p "$bin_dir"
ln -sfn "$base/current/bin/commission" "$bin_dir/commission"
case ":${PATH:-}:" in
  *":$bin_dir:"*) on_path=1 ;;
  *) on_path=0 ;;
esac

if [ "$service" = 0 ]; then
  say "done" "Commission $version is unpacked in $release (no service was installed)."
  exit 0
fi

# --- 5. The host service -----------------------------------------------------

say service "Installing the hub service…"
set -- host install --publish
[ "$yes" = 1 ] && set -- "$@" --yes
[ -n "$profile" ] && set -- "$@" --profile "$profile"
[ -n "$port" ] && set -- "$@" --port "$port"
[ -n "$data_dir" ] && set -- "$@" --data-dir "$data_dir"
cli="$release/bin/commission"
status=0
if [ "$progress" = 1 ]; then
  # Its report goes to stderr, so stdout carries only progress lines.
  "$cli" "$@" </dev/null >&2 || status=$?
elif [ ! -t 0 ] && [ -r /dev/tty ] && (exec </dev/tty) 2>/dev/null; then
  # `curl … | sh`: stdin is this script; ask the questions on the terminal.
  "$cli" "$@" </dev/tty || status=$?
else
  "$cli" "$@" || status=$?
fi
if [ "$status" -ne 0 ]; then
  die service_failed "the hub service did not start (commission host install exited $status)" \
    "fix what it reported above, then run: $bin_dir/commission host install --publish"
fi

if [ "$progress" = 1 ]; then
  printf 'progress: done %s\n' "$version"
else
  printf '\nCommission %s is installed and running.\n' "$version"
  if [ "$on_path" = 0 ]; then
    # shellcheck disable=SC2016 # $PATH is printed for the owner to paste.
    printf 'To use the commission command, add %s to your PATH, e.g. in ~/.zprofile or ~/.profile:\n  export PATH="%s:$PATH"\n' "$bin_dir" "$bin_dir"
  fi
  printf 'Next: open the Commission app on your phone and enter this machine'"'"'s tailnet address.\n'
fi
