#!/bin/bash
set -euo pipefail

# Inject the access token into the already-compiled web page.
for f in /usr/share/nginx/html/js/*.js; do
  sed -i "s/##MAPBOX_TOKEN##/${MAPBOX_TOKEN}/g" "${f}"
done
for f in /usr/share/nginx/html/js/*.js; do
  sed -i "s/##SAMSARA_API_KEY##/${SAMSARA_API_KEY}/g" "${f}"
done
for f in /usr/share/nginx/html/js/*.js; do
  sed -i "s/##ENVIRONMENT##/${ENVIRONMENT}/g" "${f}"
done
for f in /usr/share/nginx/html/js/*.js; do
  sed -i "s,##HEALTH_API##,${HEALTH_API},g" "${f}"
done
for f in /usr/share/nginx/html/js/*.js; do
  sed -i "s,##ALLOCATION_API_ENDPOINT##,${ALLOCATION_API_ENDPOINT},g" "${f}"
done

# quick sanity check that these are gone.
if grep --quiet --recursive \
    --regexp='##MAPBOX_TOKEN##' \
    --regexp='##ENVIRONMENT##' \
    --regexp='##SAMSARA_API_KEY##' \
    --regexp='##HEALTH_API##' \
    --regexp='##ALLOCATION_API_ENDPOINT##' \
    /usr/share/nginx/html/
then
  echo "Failed to replace all environment variables!"
  exit 1
fi

# Use the _first_ entry in `/etc/resolv.conf` as the resolver for Nginx. This
# guarantees that it will be able to resolve internal services (later entries
# may not).
export NAMESERVER=$( \
  cat /etc/resolv.conf \
  | grep "nameserver" \
  | awk '{print $2}' \
  | head -n1 \
  | tr '\n' ' ' \
)
echo "Nameserver is: $NAMESERVER;"

echo "Copying nginx config"
envsubst '${NAMESERVER} ${FLEETDASH_GATEWAY_API_ENDPOINT} ${HEALTH_API} ${ALLOCATION_API_ENDPOINT}' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf

echo "Using nginx config:"
cat /etc/nginx/conf.d/default.conf

echo "Starting nginx"
nginx -g "daemon off;"
