#!/bin/bash -e
# reconfigure: no
# reconfigure-title: TLS Certificate Initialization
# reconfigure-description: Generate the initial server certificates.
# Regenerate self-signed TLS/SSL cert & key

ftps_helper=/usr/lib/inithooks/bin/ftps-firstboot-cert.py
ftps_pending=false
if [[ -x "$ftps_helper" ]] && "$ftps_helper" pending; then
    ftps_pending=true
fi
[[ -n "$_TURNKEY_INIT" && "$ftps_pending" != true ]] && exit 0

[[ -e $INITHOOKS_CONF ]] && . "$INITHOOKS_CONF"

_hook=$(basename "$0")


log() {
    local level=$1
    shift
    logger -t inithooks -p "$level" "[$_hook] $*"
}

fatal() { log 3 "$*"; echo "FATAL: [$_hook] $*" 1>&2 ; exit 1 ; }
info() { log 5 "$*"; echo "INFO: [$_hook] $*" ; }


# Check for 'turnkey-make-ssl-cert' - should be provided by
# turnkey-ssl package.
turnkey_make_ssl_cert=$(which turnkey-make-ssl-cert) \
    || fatal "turnkey-make-ssl-cert executable not found."

# We use predefined 4096 bits default dhparams file for TLS1.2 (not needed for
# TLS1.3)
# See https://github.com/turnkeylinux/tracker/issues/1653 for more info.
if [[ "$ftps_pending" == true ]] && "$ftps_helper" ready; then
    info "Retrying pending FTPS activation with the existing instance certificate."
else
    info "Generating SSL/TLS cert & key."
    $turnkey_make_ssl_cert --default --force
fi

# Restart relevant services
SERVICES=(nginx apache2 lighttpd tomcat10 tomcat11 webmin pure-ftpd)

# make sure that generated keys are ready to use - avoids occasional race
# condition where cert & key don't (yet) match. a single sleep should be plenty
# but let's be sure
for _wait in {1..5}; do
    cert_md5=$(openssl x509 -noout -modulus -in /etc/ssl/private/cert.pem \
        | openssl md5)
    key_md5=$(openssl rsa -noout -modulus -in /etc/ssl/private/cert.key \
        | openssl md5)
    if [[ "$cert_md5" == "$key_md5" ]]; then
        info "SSL cert and key have been written - ready to restart services"
        break
    elif [[ $_wait -eq 1 ]]; then
        info "Waiting for updated ssl cert & key to be written to disk"
    else
        echo "..."
    fi
    sleep 1
done

if [[ "$ftps_pending" == true ]]; then
    "$ftps_helper" validate
    "$ftps_helper" mark-ready
    "$ftps_helper" activate
fi

info "Restarting relevant services."
for service in "${SERVICES[@]}"; do
    [[ "$service" == pure-ftpd && "$ftps_pending" == true ]] && continue
    # only restart services that are running
    if systemctl is-active --quiet "${service}.service"; then
        info "$service running; restarting..."
        systemctl restart --quiet "$service"
    fi
done

# final tidy up
update-ca-certificates

exit 0
