#!/bin/bash
### BEGIN INIT INFO
# Provides:          radio
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: network radio
### END INIT INFO

DIR="/usr/scripts/tv/radio/"
PIDFILE="/tmp/multicast.pid"
TMP="/tmp/"
sap_gen(){
	PREV="`md5sum /etc/sap.cfg`"
	${DIR}sap.py > /etc/sap.cfg
	NEXT="`md5sum /etc/sap.cfg`"
	if [ "$PREV" != "$NEXT" ]; then
        	/etc/init.d/minisapserver force-reload >/dev/null
	fi;
}
vlc_start() {
	if [ -f $PIDFILE ]; then
		pid=`cat $PIDFILE`
		if [ `ps -p $pid | wc -l` -eq 2 ]; then
			exit 0
		fi
	fi
	${DIR}vlm.py > ${TMP}vlm.vlm
	/usr/bin/sudo -u www-data cvlc --extraintf telnet --ttl 12 --vlm-conf ${TMP}vlm.vlm --pidfile ${PIDFILE} --daemon >/dev/null
}


vlc_stop(){
	if [ -f $PIDFILE ]; then
		pid=`cat $PIDFILE`
		kill $pid
	fi
}

vlc_status(){
	if [ -f $PIDFILE ]; then
		pid=`cat $PIDFILE`
		if [ `ps -p $pid | wc -l` -eq 2 ]; then
			echo "VLC is running."
			exit 0
		fi
	fi
	echo "VLC is NOT running."
}

usage(){
	echo "Usage: $0 {start|stop|restart}"
        exit 1
}

case $1 in
	start) 
		sap_gen;
		vlc_start;
	;;
	stop)
		vlc_stop;
	;;
	restart)
		sap_gen;
		for i in `seq 10`; do
			vlc_stop;
			sleep 1;
			if [ ! -f $PIDFILE ]; then
				break
			fi
			echo -n "."
		done
		vlc_start;
	;;
	*)
		usage;
	;;
esac
