#!/usr/bin/env bash
# Send email notification from systemd.
# Source: https://serverfault.com/questions/876233/how-to-send-an-email-if-a-systemd-service-is-restarted
# Source: https://wiki.archlinux.org/index.php/Systemd/Timers#MAILTO
# Usage: systemd-email <recipient-email> <failed-systemd-unit-name>


# According to
# http://www.flashissue.com/blog/gmail-sending-limits/
# Gmail blocks your account if you send more than 500 emails per day, which is one email every
# (24 * 60 * 60) / 500 = 172.8 second => choose a min wait time which is significantly longer than this to be on the safe time to not exceed 500 emails per day.
# However this source
# https://group-mail.com/sending-email/email-send-limits-and-options/
# says the limit when not using the Gmail webinterface but going directly to the SMTP server is 100-150 per day, which yelds maximum one email every
# (24 * 60 * 60) / 100 = 864 second
# One option that I used with my old Axis cameras it to use my gmx.com accunt for sending emails instead, as there are (no?) higher limits there.
MIN_WAIT_TIME_S=900
SCRIPT_NAME=$(basename "$0")
LAST_RUN_FILE="/tmp/${SCRIPT_NAME}_last_run.txt"

last_touch() {
	stat -c %Y "$1"
}

waited_long_enough() {
	retval=1
	if [ -e "$LAST_RUN_FILE" ]; then
		now=$(date +%s)
		last=$(last_touch "$LAST_RUN_FILE")
		wait_s=$((now - last))
		if [ "$wait_s" -gt "$MIN_WAIT_TIME_S" ]; then
			retval=0
		fi
	else
		retval=0
	fi

	[ $retval -eq 0 ] && touch "$LAST_RUN_FILE"
	return $retval
}


# Make sure that my Gmail account dont' get shut down because of sending too many emails!
if ! waited_long_enough; then
	echo "Systemd email was not sent, as it's less than ${MIN_WAIT_TIME_S} seconds since the last one was sent."
	exit 1
fi


recipient=$1
system_unit=$2

sendmail -t <<ERRMAIL
To: $recipient
From: systemd <root@$HOSTNAME>
Subject: [systemd-email] ${system_unit}
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset=UTF-8

$(systemctl status --full "$system_unit")
ERRMAIL
