#!/bin/bash
#
### BEGIN INIT INFO
# Provides:          qcontrold
# Required-Start:    $local_fs $remote_fs $syslog
# Required-Stop:     $local_fs $remote_fs $syslog
# Should-Start:      
# Should-Stop:       
# Default-Start:     S
# Default-Stop:      0 1 6
# Short-Description: Start qcontrol daemon
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

DAEMON=/usr/sbin/qcontrol
NAME=qcontrol

PIDFILE=/var/run/$NAME.pid 

test -x $DAEMON || exit 0

. /lib/lsb/init-functions

SOUND_BUZZER=yes

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

set -e

# The gpio_keys character device is required with the default
# Debian configuration file.
test_event_dev() {
	if [ ! -c /dev/input/by-path/platform-gpio-keys-event ]; then
		log_warning_msg "qcontrol error: gpio_keys device not available"
		return 1
	fi
}

case "$1" in
    start)
	test_event_dev || exit 0

	device=$(grep "Hardware[[:space:]]*:" /proc/cpuinfo 2>/dev/null | \
		 head -n1 | sed "s/^[^:]*: //")
	case $device in
	    "QNAP TS-109/TS-209" | "QNAP TS-119/TS-219" | "QNAP TS-409" | "QNAP TS-41x")
		log_daemon_msg "Starting qcontrol daemon" "qcontrol"
		if start-stop-daemon --start --quiet --oknodo --exec $DAEMON -- -d; then
			log_end_msg 0
		else
			log_end_msg 1
		fi
		;;
	    *)
		log_warning_msg "qcontrol error: device is not supported"
		;;
	esac
	;;
    stop|force-stop)
	device=$(grep "Hardware[[:space:]]*:" /proc/cpuinfo 2>/dev/null | \
		 head -n1 | sed "s/^[^:]*: //")
	case $device in
	    "QNAP TS-109/TS-209" | "QNAP TS-119/TS-219" | "QNAP TS-409" | "QNAP TS-41x")
		log_daemon_msg "Stopping qcontrol daemon" "qcontrol"
		if start-stop-daemon --stop --quiet --oknodo --exec $DAEMON; then
			log_end_msg 0
		else
			log_end_msg 1
		fi
		;;
	esac
	;;
    restart|reload|force-reload)
	$0 stop
	sleep 1
	$0 start
	;;
    status)
	;;
    *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|force-stop|restart|force-reload|status}" >&2
	exit 1
	;;
esac

exit 0
