#!/usr/bin/env bash
# Poco CLI installer.
#
# Usage:
#   curl -sSL https://get.thepoco.io | sh
#
# 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

BIN_URL="$BASE/$VERSION/poco-darwin-$ARCH"
TMP="$(mktemp -t poco-XXXXXX)"
trap 'rm -f "$TMP"' EXIT

echo "==> Downloading $BIN_URL"
if ! curl -fsSL "$BIN_URL" -o "$TMP"; then
  err "Download failed. Check connectivity to $BASE."
fi

# Strip the macOS quarantine flag (binaries are unsigned at launch).
xattr -d com.apple.quarantine "$TMP" 2>/dev/null || true

chmod +x "$TMP"

INSTALL_DIR="/usr/local/bin"
if ! [ -w "$INSTALL_DIR" ]; then
  INSTALL_DIR="$HOME/.local/bin"
  mkdir -p "$INSTALL_DIR"
  case ":$PATH:" in
    *":$INSTALL_DIR:"*) ;;
    *) echo "Note: $INSTALL_DIR is not on \$PATH. Add it to your shell profile." ;;
  esac
fi

DEST="$INSTALL_DIR/poco"
mv "$TMP" "$DEST"
trap - EXIT

echo "==> Installed $DEST"
echo "    Run \`poco --check\` to verify, then \`poco setup\` to sign in."
