#!/bin/sh

# We'll restart the server unless is ran for less than 5 minutes (300
# seconds) or was killed by one of a few signals which are treated as
# normal termination:
#   9 = SIGKILL
#   3 = SIGQUIT
#   15 = SIGTERM

restart=1
mail=1
if [ $VSRUN_SERVER_UPTIME -lt 300 ]; then
    restart=0
fi

if [ $VSRUN_SERVER_TERMSIG -eq 9 \
    -o $VSRUN_SERVER_TERMSIG -eq 3 \
    -o $VSRUN_SERVER_TERMSIG -eq 15 ]; then
    restart=0
    mail=0
fi

if [ $mail -gt 0 ]; then

    # Send a short e-mail to the user the server was running as about what
    # happened and whether we're going to restart the server.

    (
      echo "process ID $VSRUN_SERVER_PID" ;
      echo "$VSRUN_SERVER_EXPLAIN" ;
      echo ;
      if [ $restart -gt 0 ]; then
	echo "Will restart server"
      else
	echo "Will not restart server"
      fi
    ) | mail -s "Crash report for `hostname` : $VSRUN_SERVER_COMMAND" `whoami`
fi

# Exit with successful status if we mean to restart the server.
# Otherwise, exit with unsuccessful status.

if [ $restart -gt 0 ]; then
    exit 0
else
    exit 1
fi
