#!/bin/sh
# Rendered by the stock nginx entrypoint before nginx starts.
# Picks the HTTP or TLS server block depending on whether a certificate exists.
set -e

: "${DOMAIN:=localhost}"
: "${FINANCE_DOMAIN:=}"

mkdir -p /var/www/certbot

# Cert dir for the finance vhost: dedicated name if present, else DOMAIN (SAN).
FINANCE_SSL_NAME="${DOMAIN}"
if [ -n "${FINANCE_DOMAIN}" ] && [ -f "/etc/letsencrypt/live/${FINANCE_DOMAIN}/fullchain.pem" ]; then
    FINANCE_SSL_NAME="${FINANCE_DOMAIN}"
fi
export FINANCE_SSL_NAME
export FINANCE_DOMAIN
export DOMAIN

render() {
    tmpl="$1"
    if [ -n "${FINANCE_DOMAIN}" ]; then
        # Drop marker comments only; keep the finance server blocks.
        sed -e '/#__FINANCE_.*_BEGIN__/d' -e '/#__FINANCE_.*_END__/d' "$tmpl" \
            | envsubst '${DOMAIN} ${FINANCE_DOMAIN} ${FINANCE_SSL_NAME}'
    else
        # Remove optional finance server blocks entirely.
        sed -e '/#__FINANCE_.*_BEGIN__/,/#__FINANCE_.*_END__/d' "$tmpl" \
            | envsubst '${DOMAIN} ${FINANCE_DOMAIN} ${FINANCE_SSL_NAME}'
    fi
}

if [ -f "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem" ]; then
    echo "[edge] TLS certificate found for ${DOMAIN} -> enabling HTTPS"
    if [ -n "${FINANCE_DOMAIN}" ]; then
        echo "[edge] Finance portal host: ${FINANCE_DOMAIN} (ssl=${FINANCE_SSL_NAME})"
    fi
    render /etc/nginx/templates-src/edge-tls.conf.template \
        > /etc/nginx/conf.d/10-app.conf
else
    echo "[edge] No TLS certificate for ${DOMAIN} -> HTTP only (run bin/init-letsencrypt.sh)"
    if [ -n "${FINANCE_DOMAIN}" ]; then
        echo "[edge] Finance portal host: ${FINANCE_DOMAIN}"
    fi
    render /etc/nginx/templates-src/edge-http.conf.template \
        > /etc/nginx/conf.d/10-app.conf
fi
