#!/bin/bash

# This file is part of IKR SimTree
# (C) 2009-2011 University of Stuttgart, IKR

# Hook file template which is executed by SimTree when a certain condition is reached.
# The script must return with an exit value of 0, stderr and stdout of this script are ignored
# The script is only executed when the appropriate properties are enabled

# %%HOOK_FILE_SOURCE_COMMENT%%

### Parameters

# the condition, always set
CONDITION="%%CONDITION%%"

# the status (set when appropriate)
STATUS="%%STATUS%%"

# the currently executed command (set when appropriate)
COMMAND="%%COMMAND%%"

# the option list (set when appropriate)
OPTION_LIST="%%OPTION_LIST%%"

# the current Simulation parameter path (set when appropriate)
SIMPARA_PATH_STRING="%%SIMPARA_PATH_STRING%%"

############
### Methods

# Send a mail to the current user
#  $1  mail subject, if empty this is composed from the condition
#  $2  mail body, if empty then this is composed from the parameters given to the script
SendMail()
{
    local subject="$1"
    local body="$2"
    local user="$USER"
    [ -z "$user" ] && return 0
    [ -z "$subject" ] && subject="SimTree condition $CONDITION reached ($STATUS)"
  # create the message body when not given by the user
    if [ -z "$body" ]; then
      body="\nSimTree: Notifier for condition $CONDITION:\n"
      [ -n "$COMMAND" ]             && body="$body\nCommand:     $COMMAND"
      [ -n "$SIMPARA_PATH_STRING" ] && body="$body\nSimParaPath: $SIMPARA_PATH_STRING"
      [ -n "$OPTION_LIST" ]         && body="$body\n$OPTION_LIST\n"
    fi
  # send the mail
    echo -e "$body" | mail -s "$subject" "$user"
    return 0
}

############
### Main

# preset values
  [ -z "$STATUS" ] && STATUS="NotSet"

# Act according to the condition
  case "$CONDITION" in
    SIMTREE_PARENT_STARTED )
      # the SimTree parent process (called directly by the user) starts [requires NOTIFY_PARENT_CONDITION property enabled]
        SendMail
        ;;
    SIMTREE_PARENT_FINISHED )
      # the SimTree parent process (called directly by the user) is finished [requires NOTIFY_PARENT_CONDITION property enabled]
        SendMail
        ;;
    SIMTREE_CHILD_STARTED )
      # a SimTree child process (called by another SimTree process) starts [requires NOTIFY_CHILD_CONDITION property enabled]
        SendMail
        ;;
    SIMTREE_CHILD_FINISHED )
      # a SimTree child process (called by another SimTree process) is finished [requires NOTIFY_CHILD_CONDITION property enabled]
        SendMail
        ;;
    SIMULATION_STARTED )
      # a simulation/collect run starts [requires NOTIFY_SIMULATION_CONDITION property enabled]
        SendMail
        ;;
    SIMULATION_FINISHED )
      # a simulation/collect run is finished [requires NOTIFY_SIMULATION_CONDITION property enabled]
        SendMail
        ;;
  esac

# always exit with 0
  exit 0

# End of file
