#!/sbin/runscript

# This file is part of mpd-hits.
# Copyright (C) 2010 Dmitry Samoyloff.
#
# mpd-hits is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# mpd-hits is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with mpd-hits. If not, see <http://www.gnu.org/licenses/>.

DAEMON=/usr/bin/mpd-hits
DAEMON_ARGS="--daemon"
CONFIG=/etc/mpd-hits.conf

function get_config_value {
    eval $1=`grep "^[[:space:]]*$1[[:space:]]\+" $CONFIG | awk '{print $2}'`
    if [ -z ${!1} ]; then
        eerror "$1 is not specified in $CONFIG."
        return 1
    fi

    return 0
}

function read_config {
    if ! [ -f $CONFIG ]; then
        eerror "Configuration file $CONFIG does not exist."
        return 1
    fi

    get_config_value LOCK_DIRECTORY || return 1
    PIDFILE="$LOCK_DIRECTORY/mpd-hits.pid"

    get_config_value USER || return 1

    get_config_value GROUP || return 1

    return 0
}

function check_lock_dir {
    # Create lock directory if it doesn't exist
    # (say, /var/run may be mounted as temporary filesystem).
    if ! [ -d "$LOCK_DIRECTORY" ]; then
        mkdir -p "$LOCK_DIRECTORY"
        chown $USER:$GROUP "$LOCK_DIRECTORY"
        chmod 0755 "$LOCK_DIRECTORY"
    fi

    if ! [ -d "$LOCK_DIRECTORY" ]; then
        return 1
    fi

    return 0
}

depend() {
    after mpd # Can run without mpd, actually.
    need localmount # Daemon must write to local disks.
    use logger
    after bootmisc # Daemon uses /var/run.
}

start() {
    ebegin "Starting mpd-hits daemon"
    read_config || return 1
    check_lock_dir || return 1
    start-stop-daemon --start --quiet --exec "$DAEMON" --pidfile "$PIDFILE" \
        -- $DAEMON_ARGS
    eend $?
}

stop() {
    ebegin "Stopping mpd-hits daemon"
    read_config || return 1
    start-stop-daemon --stop --quiet --retry 5 --pidfile "$PIDFILE"
    eend $?
}
