#!/bin/bash
# Script para adicionar tracing a containers .NET existentes
# Uso: ./instrument-dotnet.sh <container_name> <ophion_server>

CONTAINER_NAME=$1
OPHION_SERVER=${2:-http://10.83.23.4:8080}

if [ -z "$CONTAINER_NAME" ]; then
    echo "Uso: $0 <container_name> [ophion_server]"
    echo "Exemplo: $0 siga-certificacao-api http://10.83.23.4:8080"
    exit 1
fi

# Download OTel .NET instrumentation if not exists
OTEL_DIR="/opt/otel-dotnet"
if [ ! -d "$OTEL_DIR" ]; then
    echo "📥 Baixando OpenTelemetry .NET instrumentation..."
    curl -sSL https://github.com/open-telemetry/opentelemetry-dotnet-instrumentation/releases/download/v1.7.0/opentelemetry-dotnet-instrumentation-linux-glibc-x64.zip -o /tmp/otel.zip
    mkdir -p $OTEL_DIR
    unzip -q /tmp/otel.zip -d $OTEL_DIR
    rm /tmp/otel.zip
    chmod -R 755 $OTEL_DIR
    echo "✅ OpenTelemetry instalado em $OTEL_DIR"
fi

# Get current container info
IMAGE=$(docker inspect --format='{{.Config.Image}}' $CONTAINER_NAME 2>/dev/null)
if [ -z "$IMAGE" ]; then
    echo "❌ Container $CONTAINER_NAME não encontrado"
    exit 1
fi

echo "🔄 Recriando container $CONTAINER_NAME com tracing..."

# Get container config
PORTS=$(docker inspect --format='{{range $p, $conf := .NetworkSettings.Ports}}{{if $conf}}-p {{(index $conf 0).HostPort}}:{{$p}} {{end}}{{end}}' $CONTAINER_NAME | sed 's/\/tcp//g')
NETWORK=$(docker inspect --format='{{range $net, $conf := .NetworkSettings.Networks}}{{$net}}{{end}}' $CONTAINER_NAME | head -1)

# Stop and remove old container
docker stop $CONTAINER_NAME 2>/dev/null
docker rm $CONTAINER_NAME 2>/dev/null

# Run with instrumentation
docker run -d \
    --name $CONTAINER_NAME \
    --network $NETWORK \
    $PORTS \
    -e OTEL_SERVICE_NAME=$CONTAINER_NAME \
    -e OTEL_EXPORTER_OTLP_ENDPOINT=$OPHION_SERVER \
    -e OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf \
    -e OTEL_TRACES_EXPORTER=otlp \
    -e OTEL_METRICS_EXPORTER=none \
    -e OTEL_LOGS_EXPORTER=none \
    -e CORECLR_ENABLE_PROFILING=1 \
    -e CORECLR_PROFILER="{918728DD-259F-4A6A-AC2B-B85E1B658571}" \
    -e CORECLR_PROFILER_PATH=$OTEL_DIR/linux-x64/OpenTelemetry.AutoInstrumentation.Native.so \
    -e DOTNET_ADDITIONAL_DEPS=$OTEL_DIR/AdditionalDeps \
    -e DOTNET_SHARED_STORE=$OTEL_DIR/store \
    -e DOTNET_STARTUP_HOOKS=$OTEL_DIR/net/OpenTelemetry.AutoInstrumentation.StartupHook.dll \
    -v $OTEL_DIR:$OTEL_DIR:ro \
    $IMAGE

echo "✅ Container $CONTAINER_NAME recriado com tracing!"
echo "📊 Traces serão enviados para: $OPHION_SERVER"
