#!/bin/bash

##################################################
# Mount dir                                      #
# - /etc/letsencrypt                             #
# - /var/log/letsencrypt                         #
# ENV                                            #
# - DOMAINS                                      #
##################################################

set -euo pipefail
export LANG=en_US.UTF-8
trap Quit EXIT

GOT_SIGTERM=

function Print {
    local file=/dev/null
    [ '-f' = "$1" ] && file=$2 && shift && shift
    date +"[%F %T] $*" | tee -a $file
}

function Quit {
    while :; do
        pkill -f python && Print killing python ... || break
        sleep 1
    done
    Print Container stopped.
    test -n "$GOT_SIGTERM"
}

function Usage {
    Print 'This container should run with
    **host network**
    **env DOMAINS**
    **/etc/letsencrypt and /var/log/letsencrypt mounted from host**
    '
}

function StartProc {
    if [ ! -e /etc/letsencrypt/accounts ]; then
        Print Registering ...
        certbot register --register-unsafely-without-email --agree-tos
        if echo "$DOMAINS" | grep -qo '^*'; then
            Print Requesting wildcard certificate ...
            certbot certonly -q --manual \
                --manual-auth-hook /etc/letsencrypt/manual-hook.sh \
                -d "$DOMAINS" --preferred-challenges dns \
                --server https://acme-v02.api.letsencrypt.org/directory
        else
            Print Requesting certificate ...
            certbot certonly -q -n --standalone -d $DOMAINS
        fi
        Print Generating dhparam.pem ...
        openssl dhparam -out /etc/letsencrypt/dhparam.pem 2048 \
            &>/var/log/letsencrypt/dhparam.out
        Print Succeeded to request certificate.
    else
        if echo "$DOMAINS" | grep -qo '^*'; then
            Print Renewing wildcard certificate ...
            certbot certonly --force-renewal -q --manual \
                --manual-auth-hook /etc/letsencrypt/manual-hook.sh \
                -d "$DOMAINS" --preferred-challenges dns \
                --server https://acme-v02.api.letsencrypt.org/directory
        else
            Print Renewing certificate ...
            certbot renew -q --force-renewal
        fi
        Print Succeeded to renew certificate.
    fi
}

function Main {
    Usage
    trap "GOT_SIGTERM=1; Print Got SIGTERM ..." SIGTERM
    StartProc
}

# Start here
Main

