#!/bin/sh
########################################
###### Powered by Vu+ Image Team  ######
##   http://www.vuplus-support.org    ##
########################################

DAEMON=/usr/bin/mediatomb
NAME=mediatomb
DESCRIPTION="UPNP/DLNA server"
DAEMON_ARGS="--daemon"

test -x $DAEMON || exit 0

case "$1" in
	start)
		if ( pidof $NAME >/dev/null )
		then
			echo "$NAME is running"
		else 
			echo "Starting $NAME ..."
			exec $DAEMON $DAEMON_ARGS
			sleep 2
				if ( pidof $NAME >/dev/null )
				then
					echo "$NAME starts successfully"
				else
					echo "$NAME fails to start"
				fi
		fi
	;;

	stop)
		if ( pidof $NAME >/dev/null )
			then
				echo "Stopping $NAME ..."
				MEDIATOMBPID=`pidof $NAME`
				kill $MEDIATOMBPID
				sleep 2
					if ( pidof $NAME >/dev/null )
						then
							echo "$NAME fails to stop"
						else
							echo "$NAME stops successfully"
					fi
			else 
				echo "$NAME is not running"
		fi
	;;

	autostart)
		AUTOSTART=`find /etc/rc?.d -name '*mediatomb*' -print0`
		if ! test -z $AUTOSTART
			then
				echo "Autostart for $NAME is set"
			else
				echo "Setting autostart for $NAME"
				update-rc.d -f $NAME start 30 2 3 4 . stop 10 0 1 6 .  > /dev/null 2>&1
				AUTOSTART=`find /etc/rc?.d -name '*mediatomb*' -print0`
				if ! test -z $AUTOSTART
					then
						echo "Autostart for $NAME is set"
					else
						echo "Fails to set autostart for $NAME"
						echo "Please set autostart for $NAME manually"
				fi
		fi
	;;

	noautostart)
		AUTOSTART=`find /etc/rc?.d -name '*mediatomb*' -print0`
		if ! test -z $AUTOSTART
			then
				echo "Autostart for $NAME is set"
				echo "Removing $NAME from autostart"
				update-rc.d -f $NAME remove  > /dev/null 2>&1
				AUTOSTART=`find /etc/rc?.d -name '*mediatomb*' -print0`
				if ! test -z $AUTOSTART
					then
						echo "Fails to remove autostart for $NAME"
						echo "Please remove autostart for $NAME manually"
					else
						echo "Autostart for $NAME is not set"
				fi
			else
				echo "Autostart for $NAME is not set"
		fi
	;;

	status)
		echo "***************************************************"
		if ( pidof $NAME >/dev/null )
			then
				echo "$NAME is running"
			else 
				echo "$NAME is not running"
		fi
		echo "***************************************************"
	;;

	restart)
		$0 stop
		$0 start
		exit
	;;

	*)
		echo "Usage: $0 {start|stop|restart|autostart|noautostart}" >&2
		exit 1
	;;

esac

exit 0 
