#!/usr/bin/env bash
# Audit Access Agent — Linux installer/runner
# Usage: curl -sSL https://audit.start-com.ru/download/linux | bash
set -e

RELAY_URL="${RELAY_URL:-wss://audit.start-com.ru}"
SCRIPT_URL="https://audit.start-com.ru/download/access_agent.py"
TMPDIR_AGENT="${TMPDIR:-/tmp}/audit-agent-$$"

echo ""
echo "  Audit Access Agent"
echo "  ──────────────────────────────────────────"

# Check python3
if ! command -v python3 &>/dev/null; then
    echo "  ERROR: python3 not found. Please install Python 3.8+"
    exit 1
fi

PY_VERSION=$(python3 -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
echo "  Python: $PY_VERSION"

# Install websocket-client if missing
if ! python3 -c "import websocket" 2>/dev/null; then
    echo "  Installing websocket-client..."
    python3 -m pip install websocket-client --quiet
fi

# Download access_agent.py if not already present
mkdir -p "$TMPDIR_AGENT"
AGENT_PY="$TMPDIR_AGENT/access_agent.py"

if [ -f "./access_agent.py" ]; then
    AGENT_PY="./access_agent.py"
    echo "  Using local access_agent.py"
else
    echo "  Downloading access_agent.py..."
    if command -v curl &>/dev/null; then
        curl -sSL "$SCRIPT_URL" -o "$AGENT_PY"
    elif command -v wget &>/dev/null; then
        wget -q "$SCRIPT_URL" -O "$AGENT_PY"
    else
        echo "  ERROR: curl or wget required"
        exit 1
    fi
fi

echo "  Starting agent (Ctrl+C to stop)..."
echo ""
exec python3 "$AGENT_PY" --relay "$RELAY_URL" "$@"
