#!/bin/sh /etc/rc.common
# Copyright (C) 2019 Daan Pape

START=99
STOP=20

pid_file="/var/run/dpt-faraconnect-server.pid"

get_pid() {
	cat "$pid_file"
}

is_running() {
	[ -f "$pid_file" ] && [ -e /proc/`get_pid` ]
}

start() {
	if is_running; then
		echo "Faraconnect server is already running"
	else
		echo -n "Starting Faraconnect server ..."
		/usr/sbin/dpt-faraconnect-server /etc/config/dpt-faraconnect-server >> /dev/null 2>> /dev/null &
		
		for i in {1..10}
		do
			if is_running; then
				break
		    	fi
			sleep 1
		done

		if ! is_running; then
			echo "Not Ok"
			exit 1
		else
			echo "Ok"
		fi
	fi
}

stop() {
	if is_running; then
		echo -n "Stopping Faraconnect server ..."
		kill -9 `get_pid`

		for i in {1..10}
		do
			if ! is_running; then
				break
		    	fi
			sleep 1
		done

		if is_running; then
			echo "Not Ok"
		  	exit 1
		else
			echo "Ok"
			if [ -f "$pid_file" ]; then
		    		rm "$pid_file"
		    	fi
		fi
	else
		echo "Faraconnect server wasn't running"
	fi
}

restart() {
	echo "Restarting Faraconnect server ..."
	stop;

	if ! is_running; then
		start;	
	fi
}
