#!/bin/sh
set -e

if [ -z "$SERVICE_NAME" ]; then
  echo "ERROR: SERVICE_NAME environment variable is not set"
  exit 1
fi

if [ -z "$APP_JAR" ]; then
  echo "ERROR: APP_JAR environment variable is not set"
  exit 1
fi

echo "Building OpenTelemetry Resource Attributes..."

RESOURCE_ATTRS="service.name=${SERVICE_NAME}"

if [ -n "$SERVICE_VERSION" ] && [ "$SERVICE_VERSION" != "unknown" ]; then
  RESOURCE_ATTRS="${RESOURCE_ATTRS},service.version=${SERVICE_VERSION}"
fi

RESOURCE_ATTRS="${RESOURCE_ATTRS},host.name=${HOSTNAME:-unknown}"
RESOURCE_ATTRS="${RESOURCE_ATTRS},host.ip=${POD_IP:-unknown}"

RESOURCE_ATTRS="${RESOURCE_ATTRS},k8s.pod.name=${POD_NAME:-unknown}"
RESOURCE_ATTRS="${RESOURCE_ATTRS},k8s.namespace.name=${POD_NAMESPACE:-unknown}"

if [ -n "$POD_NAMESPACE" ] && [ "$POD_NAMESPACE" != "unknown" ]; then
  RESOURCE_ATTRS="${RESOURCE_ATTRS},deployment.environment=${POD_NAMESPACE}"
fi

if [ -n "$OTEL_RESOURCE_ATTRS_EXTRA" ]; then
  RESOURCE_ATTRS="${RESOURCE_ATTRS},${OTEL_RESOURCE_ATTRS_EXTRA}"
  echo "Extra attributes added: $OTEL_RESOURCE_ATTRS_EXTRA"
fi

echo "Service Name: ${SERVICE_NAME}"
echo "Service Version: ${SERVICE_VERSION:-unknown}"
echo "App JAR: ${APP_JAR}"
echo "Resource Attributes: ${RESOURCE_ATTRS}"
echo "Starting application..."

exec java \
  ${JAVA_OPTS} \
  -javaagent:/app/opentelemetry-javaagent.jar \
  -Dotel.resource.attributes="${RESOURCE_ATTRS}" \
  ${OTEL_JAVA_OPTS} \
  -jar "${APP_JAR}"