#!/bin/bash
#
PATH=$PATH:/bin:/usr/bin:/sbin:/usr/sbin
DIR=/usr/local/fontine/bin
EXEFILE=Fontine
REALEXE=fontine
EXE=${DIR}/${EXEFILE}


checkpid() {
        while [ "$1" ]; do
           [ -d /proc/$1 ] && return 0
           shift
        done
        return 1
}

# A function to find the pid of a program.
pidofproc() {
        pidof -o $$ -o $PPID -o %PPID -x $1
}

# Log that something succeeded
success() {
        echo " OK"
        return 0
}

# Log that something failed
failure() {
        rc=$?
        echo " FAILED"
        return $rc
}

# A function to stop a program.
killproc() {
        RC=0

        # Find pid.
        pid=`pidofproc $1`

        # Kill it.
        if [ -n "${pid:-}" ] ; then
               if checkpid $pid 2>&1; then
                    # TERM first, then KILL if not dead
                     kill -TERM $pid
                     usleep 100000
                     if checkpid $pid && sleep 1 &&
                        checkpid $pid && sleep 3 &&
                        checkpid $pid ; then
                            kill -KILL $pid
                            usleep 100000
                     fi
               fi
               checkpid $pid
               RC=$?
               [ "$RC" -eq 0 ] && failure $"$1 shutdown" || success $"$1 shutdown"
               RC=$((! $RC))
        else
            failure $"$1 shutdown"
            RC=1
        fi

        return $RC
}


# Main program #

test -x ${EXE} || exit 0

cd ${DIR}

case "$1" in
    start)
	pid=`pidofproc ${REALEXE}`
	if [ "$pid" != "" ] ; then
		echo $"${REALEXE} (pid $pid) is running..."
	else
		./${EXEFILE} > /tmp/fontine.log 2>&1
		echo -n " fontine"
		echo "."
	fi
	;;
    stop)
	echo "Stopping Fontine:"
	killproc $REALEXE
	;;
  *)
    echo "Usage: /etc/init.d/fontine {start|stop}"
    exit 1
esac

exit 0
