#!/bin/sh
#
# Create a daemon out of a given processs and run it in background
# Use the created PID file to stop the process again

me_PATH="$(which $0)"
cd /

# 2. We are the child. We need to fork again.
if [ "$1" = "child" ]
then
    shift
    umask 0
    exec setsid $me_PATH refork "$@" </dev/null >/dev/null 2>/dev/null &
    exit 0
fi

# 1. This is where the original call starts.
if [ "$1" != "refork" ]
then
    if [ ! -x "$(which $1)" ]
    then
        echo "$1: Command not found."
        exit 1
    fi
    exec $me_PATH child "$@" &
    exit 0
fi

# 3. We have been reforked. Go to work.
shift
SERVICE="$1"
shift

mkdir -m 755 -p /var/log/sailmon
LOGFILE="/var/log/sailmon/${SERVICE}.log"
PIDFILE="/var/run/${SERVICE}.pid"

trap process_TERM SIGINT SIGTERM

process_TERM() {
    echo "Got signal TERM"
    kill %1
    wait
    rm ${PIDFILE}
    exit 0
}

echo $$ > ${PIDFILE}

exec >>${LOGFILE} 2>&1
exec 0</dev/null

echo "Starting as daemon: $SERVICE $@"

while [ -f $PIDFILE ]
do
    ${SERVICE} "$@" &
    wait
    sleep 2
    echo "Restarting: $SERVICE $@"
done

exit
