#!/bin/sh
echo "Replacing environment variables in index.html..."

keys="MAX_AUDIENCE_SPLIT_COUNT"

# Initialize an empty string to hold the object in JavaScript format
env_object="{"

# Loop through the keys and build the object
for key in $keys; do
    eval value=\$$key
    echo "Processing key: $key with value: $value"  # Debug statement

    # Append each key-value pair to the env_object
    env_object="${env_object}\"${key}\": \"${value}\","
done

# Remove the last comma and close the object
env_object="${env_object%,}}"

echo "Final env_object: $env_object"  # Debug statement

# Inject the object into index.html inside a <script> tag
sed -i "s|__ENV_OBJECT__|$env_object|g" "$BASE_DIR/index.html"

# Resolve the cluster DNS server(s) from the pod's /etc/resolv.conf so the
# nginx `resolver` directive is portable across clusters (EKS/GKE/kubeadm),
# whose CoreDNS ClusterIP differs by service CIDR. The kubelet writes the
# correct nameserver into every pod, so this is always the right value.
CLUSTER_DNS=$(awk '/^nameserver/ { printf "%s ", $2 } END { printf "\n" }' /etc/resolv.conf | sed 's/[[:space:]]*$//')
# Fall back to the EKS default CoreDNS ClusterIP if resolv.conf has no nameserver.
if [ -z "$CLUSTER_DNS" ]; then
    CLUSTER_DNS="172.20.0.10"
fi
echo "Using cluster DNS resolver(s): $CLUSTER_DNS"
sed -i "s|__CLUSTER_DNS__|$CLUSTER_DNS|g" /etc/nginx/conf.d/default.conf

# Start Nginx
exec nginx -g "daemon off;"
