#! /bin/sh

### BEGIN INIT INFO
# Provides:          g15daemon
# Required-Start:    $syslog $local_fs $remote_fs
# Required-Stop:     $syslog $local_fs $remote_fs
# Should-Start:      $remote_fs
# Should-Stop:       $remote_fs
# X-Start-Before:    xdm kdm gdm ldm sdm
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: load deamon for Logitech G15 keyboard lcd display
# Description:       load deamon for Logitech G15 keyboard lcd display
### END INIT INFO


PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/g15daemon
NAME=g15daemon
DESC="Logitech G15 keyboard LCD multiplexer"

[ -x "$DAEMON" ] || exit 0

. /lib/lsb/init-functions

# Include g15daemon defaults if available
if [ -f /etc/default/g15daemon ] ; then
    . /etc/default/g15daemon
fi

if [ "$G15DEBUG" = "on" ]; then

log() {
    logger -p daemon.debug -t g15 -- "$*"
}
else

log() {
    true
}

fi

check_new_init() {
    if [ -d /run/systemd/system ] ; then
        exit $1
    fi
}

load_uinput() {
    if [ ! -e /dev/uinput ] ; then
        modprobe -q uinput
        udevadm settle -t 5 -E /dev/uinput
        [ -e /dev/uinput 3 ] || return 1
    fi
}

is_running() {
   start-stop-daemon --stop --test --quiet --pidfile \
        /var/run/$NAME.pid --exec $DAEMON
}

do_start() {
    start-stop-daemon --start --quiet --pidfile /var/run/$NAME.pid \
        --exec $DAEMON -- $DAEMON_OPTS
}

do_stop() {
    start-stop-daemon --stop --quiet --pidfile /var/run/$NAME.pid \
        --oknodo --retry 5 --exec $DAEMON
}

case "$1" in
    start)
        log_daemon_msg "Starting $DESC" $NAME
        load_uinput || log_warning_msg "/dev/uinput not found"
        do_start
        log_end_msg $?
        ;;
    stop)
        log_daemon_msg "Stopping $DESC" $NAME
        if do_stop ; then
            log_end_msg 0
        else
            log_end_msg 1
            exit 1
        fi
        ;;
    force-reload)
        is_running && $0 restart || exit 0
        ;;
    restart)
        log_daemon_msg "Restarting $DESC" $NAME
        if ! do_stop ; then
            log_end_msg 1
            exit 1
        fi
        # the device is slow to shut-down
        sleep 1
        load_uinput || log_warning_msg "/dev/uinput not found"
        do_start
        log_end_msg $?
        ;;
    status)
        is_running
        exit $?
        ;;
    udev)
        check_new_init 0
        log "calling g15 udev; action: $ACTION, product $PRODUCT"
        if [ "x$ACTION" = "xadd" ] ; then
            # If g15daemon is running, it will handle replugging.
            is_running && exit 0
            load_uinput
            do_start
        fi
        ;;
    *)
        N=/etc/init.d/$NAME
        log_action_msg "Usage: $N {start|stop|restart|force-reload|status}"
        exit 1
        ;;
esac

exit 0
