#!/bin/bash

# Needed for envsubst to replace $ in final rendering
export DOLLSIGN=$

# Bash templating
cd /etc/nginx/templates
for tpl in * ; do
  if [ $tpl = "odoo.conf" ]; then
    echo '' > /etc/nginx/conf.d/$tpl
    index=0
    IFS=':' read -ra ODOO_SERVICE <<< "$ODOO_SERVICE"
    IFS=':' read -ra ODOO_SERVER_NAMES <<< "$ODOO_SERVER_NAMES"
    for service in "${ODOO_SERVICE[@]}"
    do
      SERVICE=${ODOO_SERVICE[$index]}
      SERVER_NAMES=${ODOO_SERVER_NAMES[$index]}
      PROXY_READ_TIMEOUT=${PROXY_READ_TIMEOUT:=720s}
      PROXY_CONNECT_TIMEOUT=${PROXY_CONNECT_TIMEOUT:=720s}
      PROXY_SEND_TIMEOUT=${PROXY_SEND_TIMEOUT:=720s}
      export SERVICE SERVER_NAMES PROXY_READ_TIMEOUT PROXY_CONNECT_TIMEOUT PROXY_SEND_TIMEOUT
      envsubst < $tpl >> /etc/nginx/conf.d/$tpl
      ((index++))
    done
  else
    envsubst < $tpl > /etc/nginx/conf.d/$tpl
  fi
done

# Nginx launch
nginx