#!/usr/bin/env bash
# Poco CLI installer.
#
# Usage:
#   curl -sSL https://get.thepoco.io | sh
#
# Installs the poco binary and then runs `poco setup` to finish (browser auth +
# Claude Code hooks) — one command does everything. Opt out / automate with:
#   POCO_NO_SETUP=1                                     install the binary only
#   POCO_API_KEY=pk_live_... [POCO_DASHBOARD_URL=...]   non-interactive auth
#   POCO_API_URL=...                                    API host for config.toml
#
# Honors RELEASES_BASE (default: https://get.thepoco.io) for local testing:
#   RELEASES_BASE=http://localhost:8000 bash install.sh

set -euo pipefail

BASE="${RELEASES_BASE:-https://get.thepoco.io}"
VERSION="${POCO_VERSION:-latest}"

err() { echo "error: $*" >&2; exit 1; }

OS="$(uname -s)"
case "$OS" in
  Darwin) ;;
  *) err "Unsupported OS: $OS. Only macOS is supported at launch." ;;
esac

ARCH="$(uname -m)"
case "$ARCH" in
  arm64|aarch64) ARCH=arm64 ;;
  x86_64|amd64)  ARCH=x86_64 ;;
  *) err "Unsupported architecture: $ARCH" ;;
esac

# The CLI ships as a PyInstaller onedir tree (a directory of the exe + its
# libs), tarred as poco-darwin-<arch>.tar.gz. We unpack it under <prefix>/lib/poco
# and symlink <prefix>/bin/poco at the inner exe, so `poco` stays a stable PATH
# entry while the real binary and its libs live together. onedir (vs onefile)
# avoids the onefile bootloader's SysV sync semaphore, which macOS sandboxes
# (e.g. Codex's seatbelt profile) deny - the single-file binary couldn't boot
# there.
ARCHIVE_URL="$BASE/$VERSION/poco-darwin-$ARCH.tar.gz"
STAGE="$(mktemp -d -t poco-XXXXXX)"
trap 'rm -rf "$STAGE"' EXIT

echo "==> Downloading $ARCHIVE_URL"
if ! curl -fsSL "$ARCHIVE_URL" -o "$STAGE/poco.tar.gz"; then
  err "Download failed. Check connectivity to $BASE."
fi

echo "==> Unpacking"
tar -xzf "$STAGE/poco.tar.gz" -C "$STAGE"
[ -x "$STAGE/poco/poco" ] || err "Archive did not contain an executable poco/poco."

# Strip the macOS quarantine flag from the whole tree - every bundled dylib gets
# flagged on download, and unsigned binaries need it cleared to launch.
xattr -dr com.apple.quarantine "$STAGE/poco" 2>/dev/null || true

# System-wide prefix if writable, else per-user.
PREFIX="/usr/local"
if ! [ -w "$PREFIX/bin" ]; then
  PREFIX="$HOME/.local"
fi
BINDIR="$PREFIX/bin"
LIBDIR="$PREFIX/lib/poco"
mkdir -p "$BINDIR" "$PREFIX/lib"
case ":$PATH:" in
  *":$BINDIR:"*) ;;
  *) echo "Note: $BINDIR is not on \$PATH. Add it to your shell profile." ;;
esac

# Replace any prior install, then point the stable PATH symlink at the inner exe.
rm -rf "$LIBDIR"
mv "$STAGE/poco" "$LIBDIR"
DEST="$BINDIR/poco"
ln -sf "$LIBDIR/poco" "$DEST"
trap - EXIT
rm -rf "$STAGE"

echo "==> Installed $DEST -> $LIBDIR/poco"
echo "    Licensed under the Poco Software License (see $LIBDIR/LICENSE)."
echo "    By installing and using poco you accept it."

# --- Finish setup in the same command -------------------------------------
# A bare binary isn't usable until `poco setup` has authorized the CLI and
# installed the Claude Code hooks, so we run it here — one `curl | sh` does
# everything. Escape hatches keep the one-liner safe in automation:
#   POCO_NO_SETUP=1   install the binary only
#   POCO_API_KEY=...  non-interactive auth (optionally POCO_DASHBOARD_URL=...)
#   POCO_API_URL=...  API host to write to config (default: derived by setup)
#
# TTY detection note: under `curl ... | sh` the script's *stdin* is the pipe,
# not the terminal, so `[ -t 0 ]` is false here. We gate on a usable
# controlling terminal (/dev/tty) instead, and attach setup's stdin to it so
# the browser-auth flow behaves like a normal interactive run.

setup_hint() {
  echo "    Run \`poco setup\` to sign in and install the Claude Code hooks." >&2
}

run_setup() {
  # POCO_API_URL rides as --api-url on every path; setup writes it to config.
  # ${1+"$@"} rather than "$@": macOS /bin/bash 3.2 treats an empty "$@" as
  # unbound under `set -u`.
  set --
  if [ -n "${POCO_API_URL:-}" ]; then
    set -- --api-url "$POCO_API_URL"
  fi
  if [ -n "${POCO_API_KEY:-}" ]; then
    if [ -n "${POCO_DASHBOARD_URL:-}" ]; then
      "$DEST" setup --api-key "$POCO_API_KEY" --dashboard-url "$POCO_DASHBOARD_URL" ${1+"$@"}
    else
      "$DEST" setup --api-key "$POCO_API_KEY" ${1+"$@"}
    fi
  elif [ -e /dev/tty ]; then
    "$DEST" setup ${1+"$@"} </dev/tty
  else
    "$DEST" setup ${1+"$@"}
  fi
}

if [ "${POCO_NO_SETUP:-}" = "1" ]; then
  setup_hint
elif [ -n "${POCO_API_KEY:-}" ] || [ -e /dev/tty ]; then
  echo "==> Finishing setup..."
  if ! run_setup; then
    echo "==> Binary installed, but setup didn't finish." >&2
    setup_hint
  fi
else
  # No terminal to authorize against (CI / fully non-interactive pipe).
  setup_hint
fi
