#!/bin/bash
set -e

flask migrate-database

if [ "$ENABLE_OPENTELEMETRY" = "true" ]; then
    if [ "$OTEL_TRACES_EXPORTER" = "otlp" ]; then
        export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=${OTEL_EXPORTER_OTLP_ENDPOINT:-http://localhost:4317}
        export OTEL_EXPORTER_OTLP_TRACES_TIMEOUT=${OTEL_EXPORTER_OTLP_TIMEOUT:-10000}
        export OTEL_EXPORTER_OTLP_TRACES_PROTOCOL=${OTEL_EXPORTER_OTLP_PROTOCOL:-grpc}
        export OTEL_EXPORTER_OTLP_TRACES_INSECURE=${OTEL_EXPORTER_OTLP_INSECURE:-true}
    fi

    if [ "$OTEL_METRICS_EXPORTER" = "otlp" ]; then
        export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=${OTEL_EXPORTER_OTLP_ENDPOINT:-http://localhost:4317}
        export OTEL_EXPORTER_OTLP_METRICS_TIMEOUT=${OTEL_EXPORTER_OTLP_TIMEOUT:-10000}
        export OTEL_EXPORTER_OTLP_METRICS_PROTOCOL=${OTEL_EXPORTER_OTLP_PROTOCOL:-grpc}
        export OTEL_EXPORTER_OTLP_METRICS_INSECURE=${OTEL_EXPORTER_OTLP_INSECURE:-true}
    fi

    if [ "$OTEL_LOGS_EXPORTER" = "otlp" ]; then
        export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=${OTEL_EXPORTER_OTLP_ENDPOINT:-http://localhost:4317}
        export OTEL_EXPORTER_OTLP_LOGS_TIMEOUT=${OTEL_EXPORTER_OTLP_TIMEOUT:-10000}
        export OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=${OTEL_EXPORTER_OTLP_PROTOCOL:-grpc}
        export OTEL_EXPORTER_OTLP_LOGS_INSECURE=${OTEL_EXPORTER_OTLP_INSECURE:-true}
    fi
    # otel python log settings
    export OTEL_PYTHON_LOG_CORRELATION=true
    export OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true
    export OTEL_PYTHON_FLASK_EXCLUDED_URLS="/health/*"

    opentelemetry-instrument gunicorn
else
    gunicorn
fi
