#!/bin/bash

getApiUrl (){
  # ================================================================================
  # Extract the API URL from the container's environment variables based on
  # OpenShift service conventions.
  # --------------------------------------------------------------------------------
  # API_URL:
  #  - The default URL for the API endpoint.
  #  - Used in the case API_SERVICE_NAME or one of the related service resource
  #    variables is not defined.
  #
  # API_SERVICE_NAME:
  #  - The name of the service endpoint for the API.
  #  - For example; django
  #
  # API_PATH:
  #  - The root path for the API.
  #  - For example /api/v1/
  # --------------------------------------------------------------------------------
  # Examples:
  #
  # 1)
  #   API_URL=https://django-devex-von-dev.pathfinder.gov.bc.ca/api/v1/
  #   API_SERVICE_NAME=django
  #   DJANGO_SERVICE_HOST=172.50.105.217
  #   DJANGO_SERVICE_PORT=8080
  #   API_PATH=/api/v1/
  #
  #   Results in API_URL=http://172.50.105.217:8080/api/v1/
  #
  # 2)
  #   API_URL=https://django-devex-von-dev.pathfinder.gov.bc.ca/api/v1/
  #   API_SERVICE_NAME=django
  #   DJANGO_SERVICE_HOST=172.50.105.217
  #   API_PATH=/api/v1/
  #
  #   Results in API_URL=http://172.50.105.217/api/v1/
  #
  # 3)
  #   If either API_SERVICE_NAME or *_SERVICE_HOST are not defined...
  #
  #   API_URL=https://django-devex-von-dev.pathfinder.gov.bc.ca/api/v1/
  #
  #   Results in API_URL=https://django-devex-von-dev.pathfinder.gov.bc.ca/api/v1/
  # ================================================================================
  if [ ! -z "${API_SERVICE_NAME}" ]; then
    _SERVICE_NAME="$(tr '[:lower:]' '[:upper:]' <<< ${API_SERVICE_NAME//-/_})"
    _SERVICE_HOST_NAME=${_SERVICE_NAME}_SERVICE_HOST
    _SERVICE_PORT_NAME=${_SERVICE_NAME}_SERVICE_PORT
    if [ ! -z "${!_SERVICE_HOST_NAME}" ]; then
      if [ ! -z "${!_SERVICE_PORT_NAME}" ]; then
        API_URL="http://${!_SERVICE_HOST_NAME}:${!_SERVICE_PORT_NAME}${API_PATH}"
      else
        API_URL="http://${!_SERVICE_HOST_NAME}${API_PATH}"
      fi
    fi
  fi

  echo ${API_URL}
}

API_URL=$(getApiUrl)

if [ -z "$API_URL" ]; then
  echo "Could not find API Service to proxy to, exiting"
  exit 1
fi

echo "---> Replacing Configuration ..."
echo "Setting:"
echo "RealIpFrom = ${RealIpFrom:-172.51.0.0/16}"
echo "API_URL = ${API_URL}"

sed "s~%RealIpFrom%~${RealIpFrom:-172.51.0.0/16}~g; s~%API_URL%~${API_URL}~g;" /tmp/nginx.conf.template > /etc/nginx/nginx.conf
sed "s~%RealIpFrom%~${RealIpFrom:-172.51.0.0/16}~g; s~%API_URL%~${API_URL}~g;" /tmp/nginx.conf.template
echo "---> Starting nginx ..."
/usr/sbin/nginx -g "daemon off;"
