#!/bin/sh
### BEGIN INIT INFO
# Provides:          enigma2-live555
# Required-Start:    $network dbus
# Required-Stop:     $network dbus
# Default-Start:
# Default-Stop:      0 1 6
# Short-Description: Enigma2 Live555 streaming daemon (started on demand)
### END INIT INFO

DAEMON=/usr/bin/enigma2-live555
NAME=enigma2-live555
PIDFILE=/var/run/enigma2-live555.pid
LOGFILE=/tmp/enigma2-live555.log
DEFAULTS=/etc/default/enigma2-live555

test -x "$DAEMON" || exit 0
if [ -r "$DEFAULTS" ]; then
	set -a
	. "$DEFAULTS"
	set +a
fi

is_running() {
	[ -r "$PIDFILE" ] || return 1
	pid="$(cat "$PIDFILE" 2>/dev/null)"
	case "$pid" in
		''|*[!0-9]*) return 1 ;;
	esac
	[ -d "/proc/$pid" ] || return 1
	command="$(tr '\000' '\n' < "/proc/$pid/cmdline" 2>/dev/null | head -n 1)"
	[ "$command" = "$DAEMON" ] || return 1
	kill -0 "$pid" 2>/dev/null
}

case "$1" in
	start)
		if is_running; then
			echo "$NAME is already running"
			exit 0
		fi
		rm -f "$PIDFILE"
		echo "Starting $NAME"
		echo "### starting $NAME $(date)" >> "$LOGFILE"
		if ! start-stop-daemon -S -q -b -m -p "$PIDFILE" -x "$DAEMON" >> "$LOGFILE" 2>&1; then
			echo "Failed to start $NAME"
			rm -f "$PIDFILE"
			exit 1
		fi
		;;
	stop)
		if ! is_running; then
			echo "$NAME is not running"
			rm -f "$PIDFILE"
			exit 0
		fi
		echo "Stopping $NAME"
		echo "### stopping $NAME $(date)" >> "$LOGFILE"
		start-stop-daemon -K -q -p "$PIDFILE" || true
		i=0
		while [ "$i" -lt 10 ]; do
			if ! is_running; then
				break
			fi
			sleep 1
			i=$((i + 1))
		done
		if is_running; then
			echo "Killing $NAME"
			echo "### killing $NAME $(date)" >> "$LOGFILE"
			start-stop-daemon -K -s KILL -q -p "$PIDFILE" || true
			sleep 1
		fi
		rm -f "$PIDFILE"
		;;
	restart|force-reload)
		"$0" stop
		sleep 1
		"$0" start
		;;
	status)
		if is_running; then
			echo "$NAME is running"
			exit 0
		fi
		echo "$NAME is not running"
		exit 3
		;;
	*)
		echo "Usage: $0 {start|stop|restart|force-reload|status}"
		exit 2
		;;
esac

exit 0
