#!/bin/sh

SCREWS=screwsd
#CFGFILE=/etc/screwsd.conf
LOGS=/var/log/screws.run

#---#---#---#---#---#
ERROR=""
${SCREWS} -o > /dev/null 2>&1
if [ ! "$?" = "0" ]; then
	ERROR=" * cmd '${SCREWS}' is not in PATH.\n"
fi
#if [ ! -e "${CFGFILE}" ]; then
#	ERROR="${ERROR} * Cannot find config file: '${CFGFILE}'.\n"
#fi
#if [ ! "" = "${ERROR}" ]; then
#	printf "==\n${ERROR}==\n"
#	echo "*** Please re-edit '$0' file ***"
#	exit 1
#fi
#---#---#---#---#---#
if [ "$1" = "" ]; then
	echo "Usage $0 [start|stop|restart]"
else
	case "$1" in
	"start")
		if [ ! "${ERROR}" = "" ]; then
			printf "Cannot start the server; reason: \n${ERROR}\n"
			exit 1;
		fi
		printf "Starting screwsd... "
		${SCREWS} -d > ${LOGS} 2>&1
		if [ ! "$?" = "0" ]; then
			echo "ERR"
		else
			echo "OK"
		fi
		;;
	"stop")
		PIDS=""
		printf "Stopping screwsd... "
		# /proc based systems
		if [ -e "/proc/1/status" ]; then
			cd /proc
			for A in * ; do
				if [ -e "$A/status" ]; then
				if [ ! "" = "`cat $A/status | grep screwsd`" ];
				then PIDS="$PIDS $A" ; fi
				fi
			done
			cd -
		else
			PIDS="`ps -cax | grep screwsd | awk '{print $1}'`"
		fi
echo OK
		for A in ${PIDS} ; do
			printf "$A ";
			kill -2 $A
		done
		;;
	"restart")
		$0 stop
		$0 start
		;;
	*)
	echo "Usage $0 [start|stop|restart]"
		;;
	esac
fi
exit 0;
