#!/bin/sh
# Backpack Exchange CLI installer
# Usage: curl -sSf https://install.backpack.exchange | sh

set -e

REPO="backpack-exchange/bpx-cli"
BINARY="bpx"
INSTALL_DIR="${BPX_INSTALL_DIR:-$HOME/.local/bin}"

# Detect OS and architecture
detect_platform() {
    OS="$(uname -s)"
    ARCH="$(uname -m)"

    case "$OS" in
        Linux)  OS="unknown-linux-gnu" ;;
        Darwin) OS="apple-darwin" ;;
        *)      echo "error: Unsupported OS: $OS" >&2; exit 1 ;;
    esac

    case "$ARCH" in
        x86_64|amd64)   ARCH="x86_64" ;;
        aarch64|arm64)  ARCH="aarch64" ;;
        *)              echo "error: Unsupported architecture: $ARCH" >&2; exit 1 ;;
    esac

    TARGET="${ARCH}-${OS}"
}

# Get latest release tag
get_latest_version() {
    curl -sSf "https://api.github.com/repos/${REPO}/releases/latest" | \
        grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/'
}

main() {
    detect_platform

    echo "Detecting platform... ${TARGET}"

    VERSION="$(get_latest_version)"
    if [ -z "$VERSION" ]; then
        echo "error: Could not determine latest version" >&2
        exit 1
    fi
    echo "Latest version: ${VERSION}"

    URL="https://github.com/${REPO}/releases/download/${VERSION}/bpx-${TARGET}.tar.gz"
    echo "Downloading ${URL}..."

    TMPDIR="$(mktemp -d)"
    trap 'rm -rf "$TMPDIR"' EXIT

    curl -sSfL "$URL" -o "${TMPDIR}/bpx.tar.gz"
    tar xzf "${TMPDIR}/bpx.tar.gz" -C "${TMPDIR}"

    mkdir -p "$INSTALL_DIR"
    mv "${TMPDIR}/${BINARY}" "${INSTALL_DIR}/${BINARY}"
    chmod +x "${INSTALL_DIR}/${BINARY}"

    echo ""
    echo "Installed ${BINARY} to ${INSTALL_DIR}/${BINARY}"

    # Check if install dir is in PATH
    case ":$PATH:" in
        *":${INSTALL_DIR}:"*) ;;
        *)
            echo ""
            echo "Add ${INSTALL_DIR} to your PATH:"
            echo "  export PATH=\"${INSTALL_DIR}:\$PATH\""
            ;;
    esac

    echo ""
    echo "Get started:"
    echo ""
    echo "  Try it now (no API key needed):"
    echo "    ${BINARY} markets list         View all markets"
    echo "    ${BINARY} markets ticker SOL_USDC   Get SOL price"
    echo ""
    echo "  To trade, set up your API key:"
    echo "    ${BINARY} setup                Interactive setup wizard"
    echo ""
    echo "  Verify your setup:"
    echo "    ${BINARY} status               Check connection & auth"
    echo ""
}

main
