#!/bin/sh -e

if [ -n "$MPD_DEBUG" ]; then
    set -x
    MPD_OPTS=--verbose
fi

umask 0022
PATH=/sbin:/bin:/usr/sbin:/usr/bin

# edit /etc/default/mpd to change these:
DAEMON=/usr/bin/mpd
MPDCONF=/etc/mpd.conf
START_MPD=true

if [ -r /etc/default/mpd ]; then
    . /etc/default/mpd
fi

PIDFILE=$(sed -n 's/^[[:space:]]*pid_file[[:space:]]*"\?\([^"]*\)\"\?/\1/p' $MPDCONF)
DBFILE=$(sed -n 's/^[[:space:]]*db_file[[:space:]]*"\?\([^"]*\)\"\?/\1/p' $MPDCONF)
USER=`awk 'BEGIN{ao=0} /[ \t]*audio_output[ \t]*{/{ ao = 1 } /[ \t]*}/{ ao = 0 } /^[ \t]*user[ \t]*/{ if (ao == 0) user = $2 } END{ print substr(user, 2, length(user) - 2) }' $MPDCONF`

mpd_start () {
    if [ "$START_MPD" != "true" ]; then
        echo "Not starting MPD: disabled by /etc/default/mpd."
        exit 0
    fi
    echo -n "Starting Music Player Daemon: "

    if ! (grep -q db_file $MPDCONF && grep -q pid_file $MPDCONF); then
        echo "$MPDCONF must have db_file and pid_file set; not starting."
        exit 0
    fi

    PIDDIR=$(dirname "$PIDFILE")
    if [ ! -d "$PIDDIR" ]; then
        mkdir -m 0755 $PIDDIR
        chown $USER:audio $PIDDIR
    fi

    if [ "$FORCE_CREATE_DB" -o ! -f "$DBFILE" ]; then
        echo -n "creating $DBFILE... "
        $DAEMON --create-db "$MPDCONF" > /dev/null 2>&1
    fi

    if start-stop-daemon --start --quiet --pidfile $PIDFILE \
	    --exec $DAEMON $MPD_OPTS "$MPDCONF"; then
        echo "mpd."
    else
        echo "failed."
    fi
}

mpd_stop () {
    echo -n "Stopping Music Player Daemon: "
    if start-stop-daemon --stop --quiet --retry 5 --pidfile $PIDFILE \
	    --exec $DAEMON; then
        echo "mpd."
    else
        echo "not running or no pid_file set."
    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)
        mpd_start
        ;;
    stop)
        mpd_stop
        ;;
    restart|reload)
        mpd_stop
        mpd_start
        ;;
    force-start|start-create-db)
        FORCE_CREATE_DB=1
        mpd_start
        ;;
    force-restart|force-reload)
        FORCE_CREATE_DB=1
        mpd_stop
        mpd_start
        ;;
    *)
        echo "Usage: $0 {start|start-create-db|stop|restart|reload}"
        exit 1
        ;;
esac
