#!/bin/bash
#
# Startup script for the Flumotion streaming server
#
# flumotion: Flumotion Streaming Server
#
# description: Flumotion is a streaming server for audio and video. \
#              See http://www.fluendo.com for details.
#

### BEGIN INIT INFO
# Provides:     flumotion
# Required-Start:   $local_fs $remote_fs $network
# Required-Stop:    $local_fs $remote_fs $network
# Default-Start:    3 5
# Default-Stop:     0 1 2 6
# Short-Description:    Flumotion Streaming Server
# Description:      Flumotion is a streaming server for audio and video. \
#                   See http://www.fluendo.com for details.
### END INIT INFO

#
# Determine the base and follow a runlevel link name.
#
base=${0##*/}
link=${base#*[SK][0-9][0-9]}

# Source function library.
#. /etc/rc.d/init.d/functions
. /etc/rc.status

rc_reset

# paths to files and variables
service=flumotion
prog=/usr/sbin/flumotion
lockdir=/var/lock/subsys
logfile=/var/log/flumotion/service.log
sysconfig=/etc/flumotion/sysconfig/flumotion

# source configuration
if [ -f $sysconfig ] ; then
	. $sysconfig
fi

# to make sure our service log file is always owned by the correct user
touch_logfile() {
	touch $logfile
	chown flumotion $logfile
}

# if arguments are specified, we only start/stop that service part
start() {
	if test "x$*" != "x"
	then
		startone $*
		return $?
	fi

	list=`$prog status | cut -f1,2 -d' ' | tr ' ' @`
	RETVAL=0
	for line in $list
	do
		type=`echo $line | cut -f1 -d'@'`
		name=`echo $line | cut -f2 -d'@'`
		startone $type $name || RETVAL=1
	done
        return $RETVAL
}

startone() {
	type=$1
	name=$2
	echo -n $"startone Starting $type $name: "
	startproc $prog -d 3 -l $logfile start $type $name
	RETVAL=$?
	echo
	[ $RETVAL = 0 ] && touch ${lockdir}/flumotion.$type.$name.lock
	return $RETVAL
}

stop() {
	if test "x$*" != "x"
	then
		stopone $*
		return $?
	fi

	list=`$prog status | cut -f1,2 -d' ' | tr ' ' @`
	RETVAL=0

	for line in $list
	do
		type=`echo $line | cut -f1 -d'@'`
		name=`echo $line | cut -f2 -d'@'`
		stopone $type $name || RETVAL=1
	done
	return $RETVAL
}

stopone() {
	type=$1
	name=$2

	touch_logfile

	RETVAL=0
	lockfile=${lockdir}/flumotion.$type.$name.lock
	if test -e ${lockfile}
	then
		echo -n $"Stopping $type $name: "
		$prog stop -d 3 -l $logfile $type $name
		RETVAL=$?
		[ $RETVAL = 0 ] && rm ${lockdir}/flumotion.$type.$name.lock
	echo
	fi
	return $RETVAL
}

status() {
	touch_logfile
	$prog status
}

clean() {
	touch_logfile
	$prog clean
}

list() {
	touch_logfile
	$prog list
}

# See how we were called.
case "$1" in
	start)
		shift
		start $*
		rc_status -v1
		;;
	stop)
		shift
		stop $*
		rc_status -v1
		;;
	restart|reload)
		shift
		$0 stop
		$0 start
		;;
	status)
		status
		;;
	clean)
		clean
		;;
	list)
		list
		;;
	*)
		echo $"Usage: $service {start|stop|restart|list|status|clean}"
		exit 1
esac

#exit $RETVAL
rc_exit
