#!/bin/sh

#
# Distinguish between normal jobs and an array job.
#

case `echo "$2" | cut -d " " -f 1` in

      Job) JOB_ID=`echo "$2" | cut -d " " -f 2`
           CONDITION=`echo "$2" | cut -d " " -f 4` ;;

Job-array) JOB_ID=`echo "$2" | cut -d " " -f 3`
           CONDITION=`echo "$2" | cut -d " " -f 5` ;;

        *) ;;

esac

#
# Get the entries for the context of the job and the
# reason in case of an abortion of the job.
#

if [ "$CONDITION" = "Aborted" ]; then
    if [ -f /var/spool/sge/$HOSTNAME/messages -a -r /var/spool/sge/$HOSTNAME/messages ]; then
        APPENDIX=`egrep "[|]job $JOB_ID([.][[:digit:]]+)? exceed" /var/spool/sge/$HOSTNAME/messages | head -n 1`
    fi

    if [ -z "$APPENDIX" ]; then
        APPENDIX="Unknown, no entry found in messages file on the master node of the job."
    fi
fi

#
# No construct and send the email.
#
 
if [ -n "$APPENDIX" ]; then
    (cat; echo; echo "Reason for job abort:"; echo $APPENDIX) | mail -s "$2" "$3"
else
    mail -s "$2" "$3"
fi
