#!/bin/sh
# This file is part of sakana.  See COPYING for the license.
#
# Example reporting command for sakana: mails the report it receives on
# standard input to the addresses given as arguments.  The first line of the
# report is used as the subject.
#
# Usage (from sakana.conf):
#   COMMAND = /usr/share/sakana/sakana-notify-mail ops@example.com

set -eu

if [ "$#" -lt 1 ]; then
    echo "usage: $0 ADDRESS..." >&2
    exit 64
fi

report=$(cat)
subject=$(printf '%s\n' "$report" | head -n 1)

if command -v mail >/dev/null 2>&1; then
    printf '%s\n' "$report" | mail -s "$subject" "$@"
    echo "mailed to $*"
elif command -v sendmail >/dev/null 2>&1; then
    for rcpt in "$@"; do
        {
            printf 'To: %s\n' "$rcpt"
            printf 'Subject: %s\n' "$subject"
            printf 'Content-Type: text/plain; charset=UTF-8\n\n'
            printf '%s\n' "$report"
        } | sendmail -t
    done
    echo "sent to $*"
else
    echo "neither mail(1) nor sendmail(8) is available" >&2
    exit 69
fi
