#!/bin/sh
# description: Start/stop USB B2K driver
# chkconfig: 2345 99 99

PATH=/sbin:/bin:/usr/bin:/usr/local/bin
#space separated values list here, 
#for Kubuntu the pid-file is stored in /var/run
PIDFILE_DIRS=/var/run

# Written by alatariel,Simon Dible 
# Jan 2007
# july 2007 fixed a status bug in start!
#
# Changes from original
# see http://virtuelvis.com/archives/2005/04/script-output-bitbucket for the redirect notes should be 2>&1 not 1>&2
# Added restart and status
# changed the stop to use the "ps U" command and grep as pid files are in different places on diff OS's 
# changed restart to call itsself via $0 script address !!
#
# modified for Kubuntu by Alatariel
# 

case "$1" in
'start')
    #
    # create the socket in /tmp
    #
    usbb2k_api & > /dev/null 2>&1 
	sleep 1
    RETVAL=$?
	if [ `ps -A | grep -v grep | grep -c usbb2k_api` -ge 1 ]; then
		echo "usbb2k_api started"
	else
		echo "usbb2k_api failed to start"
	fi
    sleep 1
    ;;
'stop')
	#
	#Terminate the client and skype if they are running 
	#
    killall kb2kskype > /dev/null 2>&1
    killall skype > /dev/null 2>&1
	RETVAL=0
    if [ `ps -A | grep -v grep | grep -c usbb2k_api` -ge 1 ]; then 
		killall usbb2k_api > /dev/null 2>&1
		RETVAL=$?
		#find and remove the pid-file, otherwise a start/stop/restart 
		#several times won't work!
		for PIDFILEDIR in $PIDFILE_DIRS; do 
			PIDFILE=`find $PIDFILEDIR -type f -name usbb2k_api.pid`
			if [ -e $PIDFILE ]; then 
				rm -f $PIDFILE > /dev/null 2>&1 
				STATUS=$?
				if [ $STATUS -eq 0 ]; then
					echo "pid file removed"
				fi
			fi
		done
    fi
    if [ -e /tmp/usbb2k.sock ]; then 
        rm -f /tmp/usbb2k.sock > /dev/null 2>&1 
		STATUS=$?
		if [ $STATUS -eq 0 ]; then
			echo "socket removed"
		fi
    fi
	if [ $RETVAL -eq 0 ]; then
    	echo "usbb2k_api stopped"
	else
		echo "failed to stop usbb2k_api, check you are root"
	fi
	sleep 1
   ;;
'status')
	#grep the process table but ignore grep itsself
	if [ `ps -A | grep -v grep | grep -c usbb2k_api` -ge 1 ]; then
		echo "usbb2k_api is running "
		RETVAL=0
	else
		echo "usbb2k_api is stopped"
		RETVAL=1
	fi
	;;
'restart')
	$0 stop && $0 start
	RETVAL=$?
	;;
*)
	echo "Usage: $0 { start | stop | restart | status}"
	RETVAL=1
	;;
esac
exit $RETVAL
