#!/bin/sh
#
# relaunch --start <command-line>
#
# Script to keep a program running until it exits with an okay (0) exit status.
#

PATH="/bin:/sbin:/usr/bin:/usr/sbin"
LOGGER="logger -s"
DATE="date +%s"
PROG_COMMAND="$@"
PROG_INTERVAL="10"
PROG_SHORT_UPTIME="60"
PROG_MAX_SHORT_UPTIMES="3"

if [ `uname` = "SunOS" ]; then
	LOGGER="logger"
	DATE="date +%G%m%d%H%M%S"
	# Solaris won't give us the Unix time in seconds, so we have to
	# fake it, but this format isn't continuous across minute
	# boundaries, so we have to stretch the 'short' time to
	# compensate.
	PROG_SHORT_UPTIME="100"
fi



if [ ! -x "$0" ]; then
	echo "$0 must be executable."
	exit 1
fi

if [ $# -lt 1 ]; then
	echo "Usage: $0 --start <command-line>"
	exit 1
fi
	
# If --start is the first argument on the command-line, fork and re-run
# the script in the background without the --start argument. We don't need
# to nohup; the script will do that once it is re-run.

if [ "$1" = "--start" ]; then
	if [ $# -lt 2 ]; then
		echo "Usage: $0 --start <command-line>"
		exit 1
	fi
	shift
	"$0" "$@" > /dev/null 2>&1 &
	exit 0
fi

trap "$LOGGER -t relaunch '[$$] Received TERM signal.'; exit 0" TERM
trap "$LOGGER -t relaunch '[$$] Received INT signal.'; exit 0" INT
trap "" HUP

IFS=' '

$LOGGER -t relaunch "[$$] Launch '$PROG_COMMAND' for the first time."

SHORTLAUNCHES=0
TIMESTARTED=`$DATE`
$PROG_COMMAND
exit_status=$?

while [ $exit_status -ne 0 ]; do
	$LOGGER -t relaunch "[$$] '$PROG_COMMAND' exited with status $exit_status. Relaunch in $PROG_INTERVAL seconds..."
	TIMENOW=`$DATE`
	TIMEDIFF=`expr $TIMENOW - $TIMESTARTED`
	if [ $TIMEDIFF -lt $PROG_SHORT_UPTIME ]; then
		$LOGGER -t relaunch "[$$] '$PROG_COMMAND' crashed in less than $PROG_SHORT_UPTIME seconds"
		SHORTLAUNCHES=`expr $SHORTLAUNCHES + 1`
	else
		SHORTLAUNCHES=0
	fi
	if [ $SHORTLAUNCHES -lt $PROG_MAX_SHORT_UPTIMES ]; then
		sleep $PROG_INTERVAL
		TIMESTARTED=`$DATE`
		$PROG_COMMAND
		exit_status=$?
	else
		$LOGGER -t relaunch "[$$] '$PROG_COMMAND has crashed in less than $PROG_SHORT_UPTIME seconds more than $PROG_MAX_SHORT_UPTIMES in a row, disabling."
		exit_status=0
	fi
done

$LOGGER -t relaunch "[$$] '$PROG_COMMAND' exited with status $exit_status."

exit 0
