#!/bin/bash

   ##########################################################
  #  Written 5/18/2008 and released under the GNU/GPLv2    ##
 # (c) Jeff Schroeder (jeffschroeder@computer.org)        # #
##########################################################  #
#                                                        #  #
# mailonoutput - Run a command and send an email if the  #  #
#                command returns output. This seems more #  #
#                clean than empty cron mail.             #  #
#                                                        # #
##########################################################

# $Id: mailonoutput 68027 2008-05-18 23:18:11Z jschroeder $

PATH=/bin:/usr/bin:$PATH
SUBJECT_LEN=50
EMAIL_FILE=email.txt
OUT=stdout.txt
ERR=stderr.txt

usage() {
cat << EOF >&2
Usage: $(basename $0) [EMAIL] [OPTION] [COMMAND]

OPTION
    -s "subject" - Send the email with "subject"

[COMMAND] is the only mandatory argument.

Email addresses need to be the first argument and space seperated like mail(1).
Mail is sent to, $(whoami), the default user if none is specified directly.

Examples:
    mailonoutput billg@microsoft.com df -h
    mailonoutput -s "Who is on my server?" who -u
    mailonoutput coreteam@website.com -s "Global Time Offset" /home/coreteam/scripts/globaltimeoffset
EOF
exit 1
}

if (! echo "$1" | grep -q '@'); then
    EMAIL=$(whoami)
else
    EMAIL=$1
    shift
fi

if [ ! $# -gt 1 ]; then
   usage
fi

# Some crazy logic for handling custom email subjects
if [ "$1" = "-s" ]; then
    SUBJECT=$2
    shift
    shift
# Truncate long commands for smaller subjects in your MUA
elif [ "$(echo $* | wc -c)" -gt $SUBJECT_LEN ]; then
    SUBJECT="$(echo $* | head -c$SUBJECT_LEN)..."
else
    SUBJECT="Output From: $*"
fi

FULL_COMMAND=$*

TMP_DIR=$(mktemp -d -t mailonoutput.XXXXXX)
# Require bash because not all shells trap these properly
trap "rm -rf $TMP_DIR; exit" SIGHUP SIGINT SIGTERM

cd $TMP_DIR
$FULL_COMMAND > $OUT 2> $ERR

# Create the file to email output
if [ -s $OUT ]; then
    echo "===== OUTPUT from $FULL_COMMAND =====" > $EMAIL_FILE
    cat $OUT >> $EMAIL_FILE
fi
if [ -s $ERR ]; then
    echo "===== ERRORS from $FULL_COMMAND =====" >> $EMAIL_FILE
    cat $ERR >> $EMAIL_FILE
fi

# Only email output otherwise do nothing
if [ -s "$EMAIL_FILE" ]; then
    cat $EMAIL_FILE | mail -s "$SUBJECT" $EMAIL
else
    echo "Nothing to do you tard"
fi

rm -rf $TMP_DIR
