{ pkgs, lib, config, ... }:
let
    fromAddress = config.email.fromAddress;
    fromIdentity = config.email.fromIdentity;
    toAddress = config.email.adminEmail;
    cfg = config.services.statusEmail;
in
{
    options.services.statusEmail = {
        enable = lib.mkEnableOption "Send systemd status e-mails";
    };

    config.programs.msmtp = lib.mkIf cfg.enable {
        enable = true;
        setSendmail = true;
        accounts = {
            default = {
                auth = true;
                host = "gvfr.de";
                passwordeval = "cat /secrets/email_password.txt";
                user = fromAddress;
                from = fromAddress;
                port = 465;
                tls = true;
                tls_starttls = false;
            };
        };
    };

    config.systemd.services."status-email@" = let
        sendStatusEmail = pkgs.writeScript "send-status-email" ''
            #!${pkgs.bash}/bin/bash

            from="${fromIdentity}"
            to="${toAddress}"
            service="$1"
            full_status="$(systemctl status --full --lines 200 "$service")"
            exit_code="$(echo "$full_status" | head -n5 | tail -1 | sed -e 's/.*status=\(.*\))$/\1/g')"
            # state="$(systemctl is-failed "$service")"

            fail_priority=1
            fail_subject="Unit \"$service\" failure report (exit code $exit_code)"
            success_priority=3
            success_subject="Unit \"$service\" report (success)"

            shift
            while [ $# -gt 0 ] ; do
                case "$1" in
                    '-s'|'--fail-subject')
                        fail_subject="$2"
                        shift 2
                        ;;
                    '-p'|'--fail-priority')
                        fail_priority="$2"
                        shift 2
                        ;;
                    *)
                        break
                        ;;
                esac
            done

            if [ "$exit_code" != "0/SUCCESS" ] ; then
                subject="$fail_subject"
                priority="$fail_priority"
            else
                subject="$success_subject"
                priority="$success_priority"
            fi

            echo "Sending e-mail \"$subject\" to \"$to\"."

            ${pkgs.system-sendmail}/bin/sendmail -t -X - <<ERRMAIL
            To: $to
            From: $from
            Subject: $subject
            Content-Transfer-Encoding: 8bit
            Content-Type: text/plain; charset=UTF-8
            X-Priority: $priority

            $full_status

            ERRMAIL
        '';
    in
    lib.mkIf cfg.enable {
        unitConfig = {
            Description = "Send a status e-mail for %I";
        };
        serviceConfig = {
            Type = "oneshot";
            ExecStart = "${sendStatusEmail} %i";
        };
    };
}
