#!/bin/bash
# ═══════════════════════════════════════════════════════════
# 🐍 OPHION Remote Agent Installer
# Instala agent + OTel collector + instrumenta containers .NET
# ═══════════════════════════════════════════════════════════

set -e

OPHION_SERVER="${1:-10.83.23.4}"
AGENT_KEY="${2:-ophion-secret-agent-key-2024}"
HOSTNAME_LABEL="${3:-$(hostname)}"

echo "🐍 OPHION Remote Agent Installer"
echo "================================"
echo "Server: $OPHION_SERVER"
echo "Host: $HOSTNAME_LABEL"
echo ""

# 1. Instalar OTel Collector
echo "📦 Installing OTel Collector..."

mkdir -p /opt/ophion
cat > /opt/ophion/otel-collector-config.yaml << 'OTELEOF'
receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318
  docker_stats:
    endpoint: unix:///var/run/docker.sock
    collection_interval: 30s

processors:
  batch:
    send_batch_size: 1024
    timeout: 5s
  resourcedetection:
    detectors: [system, docker]
    timeout: 5s

exporters:
  otlp:
    endpoint: OPHION_SERVER_PLACEHOLDER:4317
    tls:
      insecure: true

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [batch, resourcedetection]
      exporters: [otlp]
    metrics:
      receivers: [otlp, docker_stats]
      processors: [batch, resourcedetection]
      exporters: [otlp]
    logs:
      receivers: [otlp]
      processors: [batch, resourcedetection]
      exporters: [otlp]
OTELEOF

sed -i "s/OPHION_SERVER_PLACEHOLDER/$OPHION_SERVER/g" /opt/ophion/otel-collector-config.yaml

# Parar collector existente se houver
docker rm -f ophion-otel-collector 2>/dev/null || true

docker run -d \
  --name ophion-otel-collector \
  --restart always \
  -v /opt/ophion/otel-collector-config.yaml:/etc/otel-collector-config.yaml:ro \
  -v /var/run/docker.sock:/var/run/docker.sock:ro \
  -p 4317:4317 \
  -p 4318:4318 \
  otel/opentelemetry-collector-contrib:0.96.0 \
  --config=/etc/otel-collector-config.yaml

echo "✅ OTel Collector running"

# 2. Instrumentar containers .NET existentes
echo ""
echo "🔧 Instrumenting .NET containers..."

DOTNET_CONTAINERS=$(docker ps --format '{{.Names}}' | while read name; do
  CMD=$(docker inspect "$name" --format '{{.Config.Cmd}}' 2>/dev/null)
  ENTRYPOINT=$(docker inspect "$name" --format '{{.Config.Entrypoint}}' 2>/dev/null)
  if echo "$CMD $ENTRYPOINT" | grep -qi "dotnet"; then
    echo "$name"
  fi
done)

for CONTAINER in $DOTNET_CONTAINERS; do
  echo "  → Instrumenting $CONTAINER..."
  
  # Get current image and config
  IMAGE=$(docker inspect "$CONTAINER" --format '{{.Config.Image}}')
  
  # Get all env vars
  CURRENT_ENV=$(docker inspect "$CONTAINER" --format '{{range .Config.Env}}{{println .}}{{end}}')
  
  # Get ports
  PORTS=$(docker inspect "$CONTAINER" --format '{{range $p, $conf := .NetworkSettings.Ports}}{{range $conf}}-p {{.HostPort}}:{{$p}} {{end}}{{end}}' 2>/dev/null | sed 's|/tcp||g; s|/udp||g')
  
  # Get volumes
  VOLUMES=$(docker inspect "$CONTAINER" --format '{{range .Mounts}}-v {{.Source}}:{{.Destination}} {{end}}')
  
  echo "    Image: $IMAGE"
  echo "    Adding OTel .NET auto-instrumentation..."
  
  # Stop and remove old container
  docker stop "$CONTAINER" 2>/dev/null || true
  docker rm "$CONTAINER" 2>/dev/null || true
  
  # Rebuild with OTel env vars
  ENV_ARGS=""
  while IFS= read -r line; do
    if [ -n "$line" ]; then
      ENV_ARGS="$ENV_ARGS -e \"$line\""
    fi
  done <<< "$CURRENT_ENV"
  
  # Run with OTel instrumentation
  eval docker run -d \
    --name "$CONTAINER" \
    --restart always \
    $PORTS \
    $VOLUMES \
    $ENV_ARGS \
    -e OTEL_EXPORTER_OTLP_ENDPOINT=http://host.docker.internal:4318 \
    -e OTEL_SERVICE_NAME="$CONTAINER" \
    -e OTEL_RESOURCE_ATTRIBUTES="host.name=$HOSTNAME_LABEL" \
    -e CORECLR_ENABLE_PROFILING=1 \
    -e CORECLR_PROFILER="{918728DD-259F-4A6A-AC2B-B85E1B658571}" \
    -e OTEL_TRACES_EXPORTER=otlp \
    -e OTEL_METRICS_EXPORTER=otlp \
    -e OTEL_LOGS_EXPORTER=otlp \
    --add-host host.docker.internal:host-gateway \
    "$IMAGE"
  
  echo "    ✅ $CONTAINER instrumented"
done

echo ""
echo "🎉 OPHION Agent installation complete!"
echo ""
echo "Dashboard: http://$OPHION_SERVER:3000 (if accessible)"
echo "Collector: http://localhost:4318"
echo ""
echo "Containers instrumented:"
docker ps --format "  {{.Names}} - {{.Status}}"
