#!/bin/sh

# If `BASIC_AUTH` is not already set to 'off'.
if [[ ! "${BASIC_AUTH}" == "off" ]]; then
  # And if a username and password is set.
  if [ ! -z ${BASIC_AUTH_USERNAME+x} ] && [ ! -z ${BASIC_AUTH_PASSWORD+x} ]; then
    # Generate a basic authentication config file for Nginx.
    printf "${BASIC_AUTH_USERNAME}:$(openssl passwd -crypt ${BASIC_AUTH_PASSWORD})\n" >> /etc/nginx/.htpasswd
    # Set `BASIC_AUTH` to restricted which will tell nginx to do basic authentication.
    export BASIC_AUTH="restricted"
  fi
fi

ep /etc/nginx/*
# Find all folders within /etc/nginx/conf.d/
find /etc/nginx/conf.d/ -type d | while read DIR; do
  # envplate if found folder is not empty
  if find $DIR -mindepth 1 | read; then
    ep $DIR/*;
  fi
done
ep /etc/nginx/helpers/*

# If PHP is enabled, we override the Luascript /healthz check
echo "Setting up Healthz routing"
if [ ! -z "$NGINX_FASTCGI_PASS" ]; then
  echo "Healthz routing - using PHP"
  cp /etc/nginx/conf.d/healthz.locations.php.disable /etc/nginx/conf.d/healthz.locations
fi

if [ "$FAST_HEALTH_CHECK" == "true" ]; then
   echo "FAST HEALTH CHECK ENABLED"
   cp /etc/nginx/helpers/90_healthz_fast_check.conf.disabled /etc/nginx/helpers/90_health_fast_check.conf
fi