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

function is_not_link {
    [[ -f "$1" ]] && [[ ! -L "$1" ]]
}

function use_snakeoil_cert {
    echo "!DO NOT USE IN PRODUCTION!"
    cd /etc/nginx/keys/
    ln -sf snakeoil.crt cert.crt
    ln -sf snakeoil.key cert.key
}

case "${ENABLE_HTTPS^^}" in
    TEST|TESTING|SNAKEOIL)
    if is_not_link /etc/nginx/keys/cert.crt || is_not_link /etc/nginx/keys/cert.key; then
        echo "Using existing SSL certificates."
    elif [[ -f /etc/nginx/keys/snakeoil.crt ]] && [[ -f /etc/nginx/keys/snakeoil.key ]]; then
        echo "Using existing self-signed 'snakeoil' certificate."
        use_snakeoil_cert;
    else
        echo "Generating a self-signed 'snakeoil' certificate for testing purposes."
        mkdir -p /etc/nginx/keys/
        openssl req -x509 -nodes -newkey rsa:2048 \
            -keyout /etc/nginx/keys/snakeoil.key \
            -out /etc/nginx/keys/snakeoil.crt \
            -days 365 \
            -subj "/C=DE/ST=HH/L=Hamburg/O=openems.io/OU=OPENEMS Server/CN=*"
        use_snakeoil_cert;
    fi
    ;;

    PROD|PRODUCTION|TRUE|T|YES|Y|1)
    if [[ ! -f /etc/nginx/keys/cert.crt ]] || [[ ! -f /etc/nginx/keys/cert.key ]]; then
        echo ""
        echo "HTTPS is enabled but no SSL certificate/key found in /etc/nginx/keys/"
        echo "Please mount your SSL certificate and key to /etc/nginx/keys/cert.crt and /etc/nginx/keys/cert.key respectively."
        sleep infinity
    fi
    ;;

    *) echo "No Keys will be used.";;
esac