#!/bin/sh
home=/opt/fhem
cd $home
name_fhem="fhem.pl"
port=7072

CNT_FHEM=`ps -ef | grep $name_fhem | grep -v grep | wc -l`
if [ "$CNT_FHEM" -gt "0" ] ; then
	echo "Stopping FHEM...this takes a moment"
	perl $name_fhem $port "shutdown" &
	RETVAL=$?
	# Now sleep a bit to stop fhem
	sleep 10;
	# Now kill all other processes that are not stopped yet
	for pid in $(ps -ef | grep -v grep | grep $name_fhem | cut -c10-14); do
			echo "Killing FHEM-Process with PID: $pid";
			kill $pid &
			# Wait a moment
			sleep 3
			# Just to be sure
			if [ $(ps -p $pid|grep -c $pid) -gt 0 ]; then
				kill -9 $pid
			fi
			RETVAL=0
	done
else
	echo "FHEM already stopped"
	RETVAL=0
fi
return $RETVAL