#!/bin/bash
set -e

ENV_FILE=/opt/bridgestack/smoke-test-agent/.env
SERVICE=bridgestack-smoke-test

# Install Chrome if not present
if ! command -v google-chrome-stable &>/dev/null && ! command -v chromium-browser &>/dev/null && ! command -v chromium &>/dev/null; then
    echo "Installing Google Chrome..."
    wget -q -O /tmp/google-chrome.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
    dpkg -i /tmp/google-chrome.deb 2>/dev/null || true
    rm -f /tmp/google-chrome.deb
    # Fix any missing deps on next apt run
    echo "Note: run 'sudo apt-get install -f' if Chrome has missing dependencies."
fi

if [ -f "$ENV_FILE" ]; then
    echo "Existing configuration found at $ENV_FILE — keeping it."
else
    echo ""
    echo "=== Bridgestack Smoke Test Agent Configuration ==="
    echo ""

    read -p "Agent API Key: " AGENT_API_KEY
    read -p "Projects API URL [https://projects.bridgestack.systems]: " PROJECTS_API_URL
    PROJECTS_API_URL=${PROJECTS_API_URL:-https://projects.bridgestack.systems}
    read -p "Sentry DSN (optional, press Enter to skip): " SENTRY_DSN

    cat > "$ENV_FILE" << ENVEOF
AGENT_API_KEY=$AGENT_API_KEY
PROJECTS_API_URL=$PROJECTS_API_URL
SENTRY_DSN=$SENTRY_DSN
WS_URL=wss://projects.bridgestack.systems/ws/agent
ENVEOF

    chmod 600 "$ENV_FILE"

    echo ""
    echo "=== Configuration Summary ==="
    echo "  AGENT_API_KEY=*****${AGENT_API_KEY: -4}"
    echo "  PROJECTS_API_URL=$PROJECTS_API_URL"
    echo "  SENTRY_DSN=${SENTRY_DSN:-<not set>}"
    echo ""
    echo "Config written to $ENV_FILE"
fi

chown -R nayana:nayana /opt/bridgestack/smoke-test-agent/

systemctl daemon-reload
systemctl enable ${SERVICE}.service

if systemctl is-active --quiet ${SERVICE}.service; then
    systemctl restart ${SERVICE}.service
    echo "${SERVICE} restarted."
else
    systemctl start ${SERVICE}.service
    echo "${SERVICE} started."
fi

echo "Logs: journalctl -u ${SERVICE} -f"
