#!/bin/sh
# install.sh — download and install the prv CLI.
# Usage: curl -sSL https://provably.dev/install.sh | sh
set -e

BASE_URL="https://provably.dev/dl"
INSTALL_DIR="${PRV_INSTALL_DIR:-/usr/local/bin}"

detect_platform() {
    OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
    ARCH="$(uname -m)"
    case "$ARCH" in
        x86_64|amd64) ARCH="amd64" ;;
        aarch64|arm64) ARCH="arm64" ;;
        *) echo "Unsupported architecture: $ARCH" >&2; exit 1 ;;
    esac
    case "$OS" in
        linux|darwin) ;;
        *) echo "Unsupported OS: $OS" >&2; exit 1 ;;
    esac
    echo "${OS}/${ARCH}"
}

PLATFORM="$(detect_platform)"
OS="$(echo "$PLATFORM" | cut -d/ -f1)"
ARCH="$(echo "$PLATFORM" | cut -d/ -f2)"
BINARY="prv-${OS}-${ARCH}"
URL="${BASE_URL}/${BINARY}"

echo "Downloading prv for ${OS}/${ARCH}..."
TMP="$(mktemp)"
if command -v curl >/dev/null 2>&1; then
    curl -fsSL -o "$TMP" "$URL"
elif command -v wget >/dev/null 2>&1; then
    wget -qO "$TMP" "$URL"
else
    echo "Error: curl or wget is required" >&2; exit 1
fi

chmod +x "$TMP"

if [ -w "$INSTALL_DIR" ]; then
    mv "$TMP" "${INSTALL_DIR}/prv"
else
    echo "Installing to ${INSTALL_DIR} (requires sudo)..."
    sudo mv "$TMP" "${INSTALL_DIR}/prv"
fi

echo "prv installed to ${INSTALL_DIR}/prv"
echo ""
echo "Set your API key:  export PRV_TOKEN=\"your-api-key\""
echo "Get started:       prv auth register --name my-agent"
echo "To update:         curl -sSL https://provably.dev/install.sh | sh"
