#!/bin/sh
# 2ba.ai installer bootstrap — downloads the 2ba-installer binary from the
# public GitHub release (kapetacom/2ba-installer), verifies its checksum, and
# runs it. The binary does the real work: browser pairing, API key storage
# (0600), and per-tool configuration. It opens /dev/tty for its interactive
# menu, so this keeps working when piped:
#
#   curl -fsSL https://2ba.ai/install.sh | sh
#
# Safer variant (review first — it's a ~50-line POSIX sh bootstrap):
#   curl -fsSL https://2ba.ai/install.sh -o install.sh && sh install.sh
#
# Any flags are forwarded to the binary (--help, --dry-run, --uninstall, ...).
set -eu

repo="kapetacom/2ba-installer"
# Overridable so the smoke test (install_test.go) can point at a local mirror.
base="${TBA_INSTALLER_DOWNLOAD_BASE:-https://github.com/${repo}/releases/latest/download}"

die() { printf '\033[31merror:\033[0m %s\n' "$*" >&2; exit 1; }

# Pre-flight: name every external tool we rely on so a missing one gives an
# actionable error instead of a misleading one later on.
for tool in curl tar awk mktemp id; do
  command -v "$tool" >/dev/null 2>&1 || die "$tool is required but was not found on PATH"
done

# Refuse to run as root: we write into the current user's home, so a root run
# would target /root. The binary re-checks this before writing anything.
if [ "$(id -u)" = "0" ]; then
  die "run as a normal user, not root"
fi

case "$(uname -s)" in
  Darwin) os=darwin ;;
  Linux)  os=linux ;;
  *) die "unsupported OS: $(uname -s) (this installer supports macOS and Linux)" ;;
esac
case "$(uname -m)" in
  x86_64|amd64)  arch=amd64 ;;
  arm64|aarch64) arch=arm64 ;;
  *) die "unsupported architecture: $(uname -m)" ;;
esac

asset="2ba-installer_${os}_${arch}.tar.gz"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

printf '  * downloading 2ba-installer (%s/%s)…\n' "$os" "$arch"
curl -fsSL "$base/$asset" -o "$tmp/$asset" || die "could not download $asset"
curl -fsSL "$base/checksums.txt" -o "$tmp/checksums.txt" || die "could not download checksums.txt"

# Verify the download against the release checksums (sha256sum on Linux,
# shasum -a 256 on macOS — both print "<hash>  <file>").
want=$(awk -v f="$asset" '$2 == f { print $1 }' "$tmp/checksums.txt")
[ -n "$want" ] || die "no checksum found for $asset"
got=""
if command -v sha256sum >/dev/null 2>&1; then
  got=$(sha256sum "$tmp/$asset" | awk '{ print $1 }')
elif command -v shasum >/dev/null 2>&1; then
  got=$(shasum -a 256 "$tmp/$asset" | awk '{ print $1 }')
fi
[ -n "$got" ] || die "need sha256sum or shasum to verify the download"
[ "$want" = "$got" ] || die "checksum mismatch for $asset — try again"

tar -xzf "$tmp/$asset" -C "$tmp" || die "could not extract $asset"

bin="$tmp/2ba-installer"
[ -f "$bin" ] || die "$asset did not contain a 2ba-installer binary (unexpected archive layout)"
[ -x "$bin" ] || chmod +x "$bin"

# Run as a child (not exec) so the EXIT trap above cleans up the temp dir.
"$bin" "$@"
