#!/usr/bin/env bash
set -Eeuo pipefail

UNIT="${1:?Missing failed systemd unit name}"
RECIPIENT_FILE="${LEGO_FAILURE_EMAIL_FILE:-/etc/lego/failure-email}"

[[ -r "${RECIPIENT_FILE}" ]] || {
    printf 'No lego failure-email recipient is configured in %s\n' \
        "${RECIPIENT_FILE}" >&2
    exit 0
}

IFS= read -r RECIPIENT <"${RECIPIENT_FILE}"
[[ -n "${RECIPIENT}" ]] || exit 0

HOST="$(hostname -f 2>/dev/null || hostname)"
FROM="lego@${HOST}"
SUBJECT="Certificate renewal failed for ${HOST}"
INVOCATION_ID="$(
    systemctl show "${UNIT}" \
        --property=InvocationID \
        --value 2>/dev/null || true
)"

{
    printf 'From: lego <%s>\n' "${FROM}"
    printf 'To: %s\n' "${RECIPIENT}"
    printf 'Subject: %s\n' "${SUBJECT}"
    printf 'Content-Type: text/plain; charset=UTF-8\n'
    printf '\n'

    printf 'Certificate renewal failed.\n\n'
    printf 'Host: %s\n' "${HOST}"
    printf 'Unit: %s\n' "${UNIT}"
    printf 'Time: %s\n' "$(date --iso-8601=seconds)"

    printf '\n=== systemctl status ===\n'
    systemctl status "${UNIT}" --no-pager --full || true

    printf '\n=== journal for failed invocation ===\n'
    if [[ -n "${INVOCATION_ID}" ]]; then
        journalctl \
            _SYSTEMD_INVOCATION_ID="${INVOCATION_ID}" \
            --no-pager \
            --output=short-iso || true
    else
        journalctl \
            --unit="${UNIT}" \
            --boot \
            --no-pager \
            --output=short-iso \
            --lines=250 || true
    fi
} | /usr/sbin/sendmail -f "${FROM}" -t