#! /bin/sh -e
DAEMON=/usr/bin/mpd
test -x $DAEMON || exit 0
if [ -n "$NORMALPERSON_DEBUG" ]; then
	set -x
	alias ssd="start-stop-daemon -v"
else 
	alias ssd="start-stop-daemon -q"
fi
umask 0022
PATH=/sbin:/bin:/usr/sbin:/usr/bin
PIDFILE=/var/run/mpd.pid 
CONFLIB=/usr/share/mpd/conflib/libmpdconf
MPDCONF=/etc/mpd.conf

check_conf () {
	if [ ! -f "$MPDCONF" ]; then
		echo "Config file: $MPDCONF not found!"
		echo "Run  dpkg-reconfigure mpd  to create $MPDCONF."
		exit 0 
	fi
}

check_dbfile () {
	. $CONFLIB
	DBFILE=`get_mpdconf_key db_file || echo /var/lib/mpd/mpddb`
	if [ ! -f "$DBFILE" ]; then
		# create the DB if it's called by the installer
		if [ -n "$MPD_CREATE_DB" ]; then
			echo -n "MPD db at $DBFILE not found, creating"
			$DAEMON --create-db "$MPDCONF" > /dev/null 2>&1
			echo "."
		else
			echo "MPD db at $DBFILE not found, run: '$0 start-create-db'."
			exit 0
		fi
	fi
}

exit_if_running () {
	. $CONFLIB
	local runpid=`mpd_portused || true`
	if [ -n "$runpid" ]; then
		echo "MPD is already running: $runpid. '$0 restart' to restart."
		exit 0
	fi
}

mpd_start () {
	check_conf
	exit_if_running	
	check_dbfile
	mpd_start_only
}

mpd_start_only () {
	echo -n "Starting Music Player Daemon: mpd"
	ssd -x $DAEMON -b -m -p $PIDFILE --start -- --no-daemon "$MPDCONF"
	echo "."
}

mpd_stop () {
	echo -n "Stopping Music Player Daemon: mpd"
	ssd -p $PIDFILE --stop || echo -n "... MPD is not running"
	rm -f $PIDFILE
	echo "."
}

# a nag function about running as root (MPD defaults to running as 
# the user 'mpd' in Debian.
# Let users know if the recommended defaults are changed
test_mpd_root () {
	MPDUSER=`get_mpdconf_key user`
	[ -n "$MPDUSER" ] || MPDUSER=`whoami`
	if [ "$MPDUSER" = "root" ]; then
		echo "Warning: MPD doesn't need to run as root"
		echo "Put the following line in $MPDCONF:"
		echo "user \"mpd\""
		echo "And run: adduser mpd audio"
	fi
}

# note to self: don't call the non-standard args for this in
# {post,pre}{inst,rm} scripts since users are not forced to upgrade
# /etc/init.d/mpd when mpd is updated
case "$1" in
	start|stop)
		mpd_${1}
		;;
	force-start|start-create-db)
		export MPD_CREATE_DB=1
		mpd_start
		;;
	restart|reload)
		# TODO for 0.11.0: send SIGHUP to MPD to reload the conf
		mpd_stop
		mpd_start
		;;
	force-restart|force-reload)
		export MPD_CREATE_DB=1
		mpd_stop
		mpd_start
		;;
	force-stop)
		mpd_stop
		killall mpd || true
		sleep 2
		killall -9 mpd || true
		;;
	*)
		echo "Usage: /etc/init.d/mpd {start|start-create-db|stop|restart|reload}"
		echo "force- may be prefixed to any argument to force the action"
		exit 1
		;;
esac

exit 0
