#! /usr/bin/zsh -feu

usage()
{
    cat <<EOF
Usage: $0 [-s subject] cmd args

Invoke "CMD args", redirecting its output (also stderr!) into a file, and
email it at the end.

If the exit status is 0, the email subject starts with "OK [subject]",
otherwise "FAIL [subject]".
EOF
}

# fallback (if empty)
: ${MAILTO:=Michal.Maruska@tomtom.com}
# or SENDER
: ${MAILFROM:=Michal.Maruska@tomtom.com}
# <CRON-DAEMON>"

debug=n
while getopts :dhs: OPT; do
    case $OPT in
	h|+h)
	    usage
	    exit 0
	    ;;
	d)
	    debug=y
	    ;;
	s)
	    subject=$OPTARG
	    ;;
	*)
	    usage >&2
	    exit 2
    esac
done
shift OPTIND-1
OPTIND=1

CMD=$1; shift
TEMP=$(mktemp $CMD.XXXX.log)

# how to suppress the exit-on-failure here?
if $CMD "$@" &> $TEMP;
then
    result=0
else
    result=$?
#    echo "this way $result"
fi

# default/fall-back value
: ${subject=$CMD}


if [ $result = 0 ];
then
    subject="OK $subject"
else
    subject="FAIL $subject"
fi

# stderr during this command is not controlled:
# and it might invoke gnome-keyring.
mail -r "$MAILFROM" -s $subject -a "X-sender: cron-daemon" $MAILTO < $TEMP

# need to find out why no mail arrived.
if [ $debug = y ]; then
    echo $TEMP
else
    rm $TEMP
fi

