#!/bin/bash
#
# cdemu-daemon: CDEmu userspace daemon
#

DAEMON=/usr/bin/cdemud

# Sanity checks.
if [ ! -x $DAEMON ]; then
    echo "Daemon binary $DAEMON not found!"
    exit 1
fi

# Source function library.
[ -e /lib/lsb/init-functions ] && . /lib/lsb/init-functions
[ -e /etc/default/rcS ] && . /etc/default/rcS

# Source config
if [ -f /etc/default/cdemu-daemon ]; then
    . /etc/default/cdemu-daemon
fi

RETVAL=0

start() {
    # Load module
    if [ -n "$MODULE" ]; then
        log_action_begin_msg "Inserting kernel module ($MODULE)"
        /sbin/modprobe $MODULE >/dev/null 2>&1
        RETVAL=$?
        log_action_end_msg $RETVAL
        if [ $RETVAL -ne 0 ]; then
            return $RETVAL
        fi
    fi
    
    # Wait until control device is created...
    if [ -n "$CTL_DEVICE" ]; then
        log_action_begin_msg "Waiting for $CTL_DEVICE to be created: "
        until [ -c "$CTL_DEVICE" ]; do
            echo -n ""
        done
    fi

    RETVAL=0
    log_action_end_msg $RETVAL
    if [ $RETVAL -ne 0 ]; then
        return $RETVAL
    fi

    # Daemon arguments
    DAEMON_ARGS="--daemonize"
    
    if [ -n "$DEVICES" ]; then
        DAEMON_ARGS="$DAEMON_ARGS --num-devices=$DEVICES"
    fi
    if [ -n "$CTL_DEVICE" ]; then
        DAEMON_ARGS="$DAEMON_ARGS --ctl-device=$CTL_DEVICE"
    fi
    if [ -n "$AUDIO_BACKEND" ]; then
        DAEMON_ARGS="$DAEMON_ARGS --audio=$AUDIO_BACKEND"
    fi
    if [ -n "$AUDIO_DEVICE" ]; then
        DAEMON_ARGS="$DAEMON_ARGS --audio-device=$AUDIO_DEVICE"
    fi

    # Start daemon
    log_action_begin_msg "Starting daemon"
    start-stop-daemon --start --quiet --exec $DAEMON -- $DAEMON_ARGS >/dev/null 2>&1
    RETVAL=$?
    log_action_end_msg $RETVAL
    
    return $RETVAL
}

stop() {
    # Kill daemon
    log_action_begin_msg "Killing daemon"
    $DAEMON -k >/dev/null 2>&1
    if [ $RETVAL -eq 0 ]; then
        start-stop-daemon --stop --retry=1 --quiet --oknodo --exec $DAEMON >/dev/null 2>&1
        RETVAL=$?
    fi
    log_action_end_msg $RETVAL
    
    if [ $RETVAL -ne 0 ]; then
        return $RETVAL
    fi
    
    # Unload module
    log_action_begin_msg "Removing kernel module ($MODULE)"
    /sbin/rmmod $MODULE >/dev/null 2>&1
    RETVAL=$?
    log_action_end_msg $RETVAL
        
    return $RETVAL
}

# See how we were called.
case "$1" in
    start)
        log_daemon_msg "Starting CDEmu daemon"
        start
        log_end_msg $?
        ;;
    stop)
        log_daemon_msg "Stopping CDEmu daemon"
        stop
        log_end_msg $?
        ;;
    restart)
        $0 stop
        if [ $? -eq 0 ]; then
            sleep 3
            $0 start
        fi
        ;;
    force-reload|reload)
        echo "Not implemented!"
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|force-reload|reload}"
        ;;
esac

exit $RETVAL
