#!/bin/sh
# ADBKit agent installer for macOS and Linux.
#
#   curl -fsSL https://adbkit.com/install.sh | sh
#   curl -fsSL https://adbkit.com/install.sh | sh -s -- --port 8730
#
# What this script does, and nothing else:
#   1. Detects your OS and CPU (darwin/linux, amd64/arm64).
#   2. Downloads adbkit-agent_<os>_<arch> and checksums.txt from
#      https://adbkit.com/agent/ and verifies the SHA-256 checksum. A
#      mismatch aborts; nothing is run.
#   3. Saves the binary to ~/.adbkit/bin/adbkit-agent (no sudo, no PATH edits)
#      and, on macOS, removes the download quarantine flag from that one file.
#   4. Runs the agent in the foreground. Press Ctrl+C to stop it.
# If the binary cannot be downloaded and Node.js 18+ is installed, it falls
# back to https://adbkit.com/adbkit-bridge.mjs (no Wireless debugging pairing).
# No telemetry. Nothing is installed anywhere else.
#
# Environment: ADBKIT_NO_RUN=1 (install only), ADBKIT_RELEASE_BASE and
#   ADBKIT_NODE_URL (override download locations, for testing).
# Flags: --port <n> is passed to the agent.

set -eu

BASE="${ADBKIT_RELEASE_BASE:-https://adbkit.com/agent}"
NODE_URL="${ADBKIT_NODE_URL:-https://adbkit.com/adbkit-bridge.mjs}"
HOME_DIR="${ADBKIT_HOME:-$HOME/.adbkit}"
BIN_DIR="$HOME_DIR/bin"

say() { printf '%s\n' "$*"; }
fail() { printf 'adbkit: %s\n' "$*" >&2; exit 1; }

# Parse --port (the only flag); keep the rest for the agent.
PORT_ARGS=""
PORT_VALUE=""
while [ "$#" -gt 0 ]; do
  case "$1" in
    --port)
      [ "$#" -ge 2 ] || fail "--port needs a number"
      PORT_VALUE="$2"
      shift 2
      ;;
    --port=*)
      PORT_VALUE="${1#--port=}"
      shift
      ;;
    -h|--help)
      sed -n '2,24p' "$0" 2>/dev/null || say "See https://adbkit.com/blog/adbkit-wifi-helper-setup"
      exit 0
      ;;
    *) fail "unknown option: $1" ;;
  esac
done
if [ -n "$PORT_VALUE" ]; then
  case "$PORT_VALUE" in
    ''|*[!0-9]*) fail "--port must be a number" ;;
  esac
  PORT_ARGS="--port"
fi

detect_platform() {
  os_raw="${ADBKIT_OS:-$(uname -s)}"
  arch_raw="${ADBKIT_ARCH:-$(uname -m)}"
  case "$os_raw" in
    Darwin|darwin) OS="darwin" ;;
    Linux|linux) OS="linux" ;;
    *) fail "unsupported OS: $os_raw (on Windows use: irm https://adbkit.com/install.ps1 | iex)" ;;
  esac
  case "$arch_raw" in
    x86_64|amd64) ARCH="amd64" ;;
    arm64|aarch64) ARCH="arm64" ;;
    *) fail "unsupported CPU architecture: $arch_raw" ;;
  esac
}

# download <url> <destination>; returns non-zero on failure.
download() {
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL --retry 2 -o "$2" "$1"
  elif command -v wget >/dev/null 2>&1; then
    wget -q -O "$2" "$1"
  else
    fail "need curl or wget to download files"
  fi
}

sha256_of() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | cut -d ' ' -f 1
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | cut -d ' ' -f 1
  else
    fail "need sha256sum or shasum to verify the download"
  fi
}

run_node_fallback() {
  command -v node >/dev/null 2>&1 || return 1
  node_major="$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)"
  [ "$node_major" -ge 18 ] 2>/dev/null || return 1
  mkdir -p "$BIN_DIR"
  say "Falling back to the Node.js edition (Node $node_major)."
  download "$NODE_URL" "$BIN_DIR/adbkit-bridge.mjs" || return 1
  say "Note: Wireless debugging pairing (Android 11+ pairing code) is NOT available"
  say "in the Node.js edition. USB-less \"adb tcpip\" Wi-Fi works."
  if [ "${ADBKIT_NO_RUN:-}" = "1" ]; then
    say "Installed $BIN_DIR/adbkit-bridge.mjs (not started: ADBKIT_NO_RUN=1)."
    exit 0
  fi
  say "Return to ADBKit in your browser and choose Connect over Wi-Fi."
  say "Press Ctrl+C to stop."
  if [ -n "$PORT_ARGS" ]; then
    exec node "$BIN_DIR/adbkit-bridge.mjs" --port "$PORT_VALUE"
  fi
  exec node "$BIN_DIR/adbkit-bridge.mjs"
}

detect_platform
ASSET="adbkit-agent_${OS}_${ARCH}"
TMP="$(mktemp -d "${TMPDIR:-/tmp}/adbkit.XXXXXX")"
trap 'rm -rf "$TMP"' EXIT INT TERM

say "ADBKit agent: $OS/$ARCH"
if download "$BASE/$ASSET" "$TMP/$ASSET" && download "$BASE/checksums.txt" "$TMP/checksums.txt"; then
  expected="$(awk -v f="$ASSET" '$2 == f || $2 == "*" f { print $1; exit }' "$TMP/checksums.txt")"
  [ -n "$expected" ] || fail "checksums.txt has no entry for $ASSET; refusing to run it"
  actual="$(sha256_of "$TMP/$ASSET")"
  if [ "$expected" != "$actual" ]; then
    fail "checksum mismatch for $ASSET (expected $expected, got $actual); nothing was installed"
  fi
  say "Checksum OK (sha256 $actual)."
  mkdir -p "$BIN_DIR"
  cp "$TMP/$ASSET" "$BIN_DIR/adbkit-agent"
  chmod +x "$BIN_DIR/adbkit-agent"
  if [ "$OS" = "darwin" ]; then
    xattr -d com.apple.quarantine "$BIN_DIR/adbkit-agent" 2>/dev/null || true
  fi
  say "Installed $BIN_DIR/adbkit-agent"
  if [ "${ADBKIT_NO_RUN:-}" = "1" ]; then
    say "Not started (ADBKIT_NO_RUN=1). Run it with: $BIN_DIR/adbkit-agent"
    exit 0
  fi
  say ""
  say "Starting the agent. Return to ADBKit in your browser (https://adbkit.com/app)"
  say "and choose Connect over Wi-Fi. Press Ctrl+C to stop."
  rm -rf "$TMP"
  trap - EXIT INT TERM
  if [ -n "$PORT_ARGS" ]; then
    exec "$BIN_DIR/adbkit-agent" --port "$PORT_VALUE"
  fi
  exec "$BIN_DIR/adbkit-agent"
fi

say "Could not download the agent binary from $BASE."
if run_node_fallback; then exit 0; fi

cat >&2 <<MSG

adbkit: could not install the agent automatically. Next steps:
  1. Check your internet connection and try again, or
  2. Download adbkit-agent_${OS}_${ARCH} manually from
     $REPO_URL and run it, or
  3. Install Node.js 18+ (https://nodejs.org) and run:
       curl -fsSL $NODE_URL -o adbkit-bridge.mjs && node adbkit-bridge.mjs
Docs: https://adbkit.com/blog/adbkit-wifi-helper-setup
MSG
exit 1
