#!/usr/bin/env sh
set -eu

ORIGIN="${AGENTSLOT_DOWNLOAD_ORIGIN:-https://app.agentslot.ai}"
DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"
INSTALL_DIR="${AGENTSLOT_CLI_DIR:-$DATA_HOME/agentslot/cli}"
BIN_DIR="${AGENTSLOT_BIN_DIR:-$HOME/.local/bin}"

OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
case "$OS" in
  darwin|linux) ;;
  *)
    echo "Unsupported operating system: $OS" >&2
    exit 1
    ;;
esac

RAW_ARCH="$(uname -m)"
case "$RAW_ARCH" in
  x86_64|amd64) ARCH="amd64" ;;
  arm64|aarch64) ARCH="arm64" ;;
  *)
    echo "Unsupported CPU architecture: $RAW_ARCH" >&2
    exit 1
    ;;
esac

ASSET="agentslot-${OS}-${ARCH}.tar.gz"
mkdir -p "$INSTALL_DIR" "$BIN_DIR"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT

echo "Downloading agentslot CLI (${OS}/${ARCH}) from ${ORIGIN} ..."
curl -fsSL "${ORIGIN}/downloads/agentslot/${ASSET}" -o "$TMP_DIR/$ASSET"

if curl -fsSL "${ORIGIN}/downloads/agentslot/SHA256SUMS" -o "$TMP_DIR/SHA256SUMS" 2>/dev/null; then
  EXPECTED="$(awk -v name="$ASSET" '$2 == name {print $1; exit}' "$TMP_DIR/SHA256SUMS")"
  if [ -n "$EXPECTED" ]; then
    if command -v sha256sum >/dev/null 2>&1; then
      ACTUAL="$(sha256sum "$TMP_DIR/$ASSET" | awk '{print $1}')"
    elif command -v shasum >/dev/null 2>&1; then
      ACTUAL="$(shasum -a 256 "$TMP_DIR/$ASSET" | awk '{print $1}')"
    else
      ACTUAL=""
    fi
    if [ -n "$ACTUAL" ] && [ "$ACTUAL" != "$EXPECTED" ]; then
      echo "SHA-256 verification failed for ${ASSET}; aborting install." >&2
      exit 1
    fi
  fi
fi

tar -xzf "$TMP_DIR/$ASSET" -C "$INSTALL_DIR"
chmod 755 "$INSTALL_DIR/agentslot"
ln -sf "$INSTALL_DIR/agentslot" "$BIN_DIR/agentslot"

echo ""
echo "Installed: $BIN_DIR/agentslot"
case ":${PATH:-}:" in
  *":$BIN_DIR:"*) ;;
  *)
    echo ""
    echo "Note: $BIN_DIR is not in your PATH yet. Add it with:"
    echo "  export PATH=\"$BIN_DIR:\$PATH\""
    ;;
esac
echo ""
echo "Next steps:"
echo "  agentslot info                 # Inspect platform endpoints, tiers and protocols"
echo "  agentslot skill install        # Install AgentSlot Skill for Claude Code / Codex / Cursor"
echo "  agentslot auth login           # Sign in via browser device code"
echo "  agentslot doctor               # Verify gateway, token and local coding tools"
