#!/bin/sh

# call like this in a systemd unit file:
# ExecStopPost=notify-unit-failure $N %H %u $EXIT_CODE $SERVICE_RESULT %u

if [ -z $6 ]; then
   echo "need 6 parameters: UNIT HOST USER EXIT_CODE SERVICE_RESULT RECIPIENT"
   exit 1
fi

UNIT=$1
HOST=$2
USER=$3
EXIT_CODE=$4
SERVICE_RESULT=$5
RECIPIENT=$6

# do not send email if the service result was success
test "$SERVICE_RESULT" = "success" && exit 0

domain="$(hostname --fqdn)"
recipient="${RECIPIENT:-root@$domain}"
recipients=`echo $recipient | sed 's/^/</g; s/,/>,</g; s/$/\>/'`
sender="$USER@$domain"
status="$(systemctl --user status "$UNIT")"
logs="$(journalctl --user --no-pager -n 20 -u "$UNIT")"

echo "From: <$sender>\nTo: $recipients\nSubject: [$HOST $USER] $UNIT $EXIT_CODE\n\n$status\n$logs" | sendmail -t

