#!/usr/bin/with-contenv bash
# shellcheck shell=bash

function apply_teplates {
    local pattern=$1
    local nullglob_set=0

    if ! shopt -p | grep -q 'nullglob[[:space:]]*off'; then
        nullglob_set=1 shopt -s nullglob
    fi

    for file in $pattern; do
        env_template="$file"
        env_file="${file%.tpl}"
        rm -f "$env_file";
        envsubst '$WEBSOCKET_HOST,$WEBSOCKET_PORT,$REST_PORT' < "$env_template" > "$env_file";
        sed -i '1i# This file might be deleted after the next restart'  "$env_file";
    done

    if (( nullglob_set )); then
        shopt -u nullglob
    fi
}

function enable_http {
    apply_teplates /etc/nginx/site-confs/80-*.tpl;
}

function enable_https {
    apply_teplates /etc/nginx/site-confs/443-*.tpl;

    # copy pre-generated dhparams or generate if needed
    if [[ ! -f /etc/nginx/dhparams.pem ]]; then
        rsync -av --chown=abc:abc /defaults/nginx/dhparams.pem.sample /etc/nginx/dhparams.pem
    fi

    if ! grep -q 'PARAMETERS' "/etc/nginx/dhparams.pem"; then
        curl -o /etc/nginx/dhparams.pem -L "https://ssl-config.mozilla.org/ffdhe4096.txt"
    fi
}

# copy default config files if they don't exist
rsync -av --chown=abc:abc --ignore-existing /defaults/nginx/ /etc/nginx/

mkdir -p /etc/nginx/site-confs

if [[ "$WEBSOCKET_HOST" == "<hostname>" ]]; then
    echo ""
    echo "WEBSOCKET_HOST contains <hostname> placeholder, replace it with the actual hostname or IP address of the Docker host."
    sleep infinity
fi

case "${ENABLE_HTTPS^^}" in
    TEST|TESTING|SNAKEOIL|PROD|PRODUCTION|TRUE|T|YES|Y|1) enable_https ;;
    *) echo "HTTPS is disabled." ;;
esac

enable_http;
