#!/bin/bash
set -e

echo "=== BI Agentes Startup ==="

# Check for Netbird setup key
if [ -n "$NETBIRD_SETUP_KEY" ]; then
    echo "Connecting to Netbird network..."
    echo "Management URL: ${NETBIRD_MANAGEMENT_URL:-https://netbird.cambioreal.com}"

    # Start netbird daemon directly (not via systemd - doesn't work in containers)
    MGMT_URL="${NETBIRD_MANAGEMENT_URL:-https://netbird.cambioreal.com}"

    # Run netbird daemon in background
    netbird service run &
    sleep 3

    # Connect using setup key and management URL
    # Use custom hostname for stable DNS name (default: bi-ccc)
    NETBIRD_HOSTNAME="${NETBIRD_HOSTNAME:-bi-ccc}"
    netbird up --setup-key "$NETBIRD_SETUP_KEY" --management-url "$MGMT_URL" --hostname "$NETBIRD_HOSTNAME" &

    # Wait for connection
    echo "Waiting for Netbird connection..."
    sleep 10

    # Check connection status
    netbird status || echo "Netbird connection pending..."

    # Add route for local network to bypass VPN tunnel
    # This ensures responses to LAN clients go via Docker bridge, not VPN
    echo "Adding local network route..."
    ip route add 192.168.88.0/24 via 172.23.0.1 dev eth0 2>/dev/null || true
else
    echo "WARNING: NETBIRD_SETUP_KEY not set. Database connection may fail."
fi

echo "Starting BI Agentes server..."
exec node server.js
