#!/bin/sh

### BEGIN INIT INFO
# Provides: gmediarender
# Required-Start: $remote_fs $syslog $all 
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start GMediaRender at boot time
# Description: Start GMediaRender at boot time.
### END INIT INFO

# User and group the daemon will be running as. On the Raspberry Pi, let's use
# the default user.
DAEMON_USER="pi:audio"

# Device name as it will be advertised to and shown in the UPnP controller UI.
# Some string that helps you recognize the player, e.g. "Livingroom Player"
UPNP_DEVICE_NAME="Raspberry"

# Initial volume in decibel. 0.0 is 'full volume', -10 correspondents to '75' on
# the exported volume scale (Note, this does not change the ALSA volume, only
# internal to gmrender. So make sure to leave the ALSA volume always to 100%).
INITIAL_VOLUME_DB=-10

# If you explicitly choose a specific ALSA device here (find them with 'aplay -L'), then
# gmediarenderer will use that ALSA device to play audio.
# Otherwise, whatever default is configured for gstreamer for the '$DAEMON_USER' is
# used.
ALSA_DEVICE="sysdefault"
#ALSA_DEVICE="iec958"

# Path to the gmediarender binary.
BINARY_PATH=/usr/local/bin/gmediarender

if [ -n "$ALSA_DEVICE" ] ; then
	GS_SINK_PARAM="--gstout-audiosink=alsasink"
	GS_DEVICE_PARAM="--gstout-audiodevice=$ALSA_DEVICE"
fi

# A simple stable UUID, based on this systems' first ethernet devices MAC address,
# only using tools readily available to generate.
UPNP_UUID=`ip link show | awk '/ether/ {print "salt:)-" $2}' | head -1 | md5sum | awk '{print $1}'`

USER=root
HOME=/root
export USER HOME
case "$1" in
	start)
		echo "Starting GMediaRender"
		start-stop-daemon -x $BINARY_PATH -c "$DAEMON_USER" -S -- -f "$UPNP_DEVICE_NAME" -d -u "$UPNP_UUID" $GS_SINK_PARAM $GS_DEVICE_PARAM --gstout-initial-volume-db=$INITIAL_VOLUME_DB
		;;

	stop)
		echo "Stopping GMediaRender"
		start-stop-daemon -x $BINARY_PATH -K
		;;

	*)
		echo "Usage: /etc/init.d/gmediarender {start|stop}"
		exit 1
		;;
esac

exit 0
