#!/bin/bash

TARGETDIR="`dirname ${0}`/.."

. ${TARGETDIR}/install.vars
. ${TARGETDIR}/bin/run.conf

cd ${TARGETDIR}

case $1 in
	start)
		PID=`/usr/bin/ps -Af -o pid,ppid,args | grep 'app=CrashPlanService' | grep -v grep | cut -f2 -d' '`
		if [ -n "$PID" ]; then
		  echo CrashPlan is already running with pid $PID
		  exit 1;
		fi
		echo "Starting CrashPlan Engine ... "
		nice -n 19 ${JAVACOMMON} ${SRV_JAVA_OPTS} -classpath "./lib/com.backup42.desktop.jar:./lang" com.backup42.service.CPService > ${TARGETDIR}/log/engine_output.log 2> ${TARGETDIR}/log/engine_error.log & 
		if [ $! -gt 0 ]; then
			echo $! > ${TARGETDIR}/CrashPlanEngine.pid
			echo "OK"
		else
			echo "FAIL" 
			exit 1
		fi
		;;
	stop)
		echo "Stopping CrashPlan Engine ... "
		if [ -f ${TARGETDIR}/CrashPlanEngine.pid ] ; then
		  kill `cat ${TARGETDIR}/CrashPlanEngine.pid`
		  sleep 5
		fi
		PID=`/usr/bin/ps -Af -o pid,ppid,args | grep 'app=CrashPlanService' | grep -v grep | cut -f2 -d' '`
		if [ -n "$PID" ]; then
		  echo Still running, killing PID=$PID
		  kill -9 $PID
		fi
		rm -f ${TARGETDIR}/CrashPlanEngine.pid
		echo "OK"
		;;
	*) 	
		echo "$0 <start|stop>"
		exit 1
		;;
esac
