#!/bin/bash
#
### BEGIN INIT INFO
# Provides:          qcontrol
# Required-Start:    qcontrold $remote_fs $all
# Required-Stop:     qcontrold $remote_fs
# Should-Start:      
# Should-Stop:       
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Change status leds for QNAP Turbo Station devices
### 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

case "$1" in
    start)
	# TODO: check that daemon is running
	# Change status led to show green
	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")
		log_action_msg "System boot completed"
		qcontrol statusled greenon
		qcontrol powerled on
		if [ "$SOUND_BUZZER" != no ]; then
			qcontrol buzzer short
		fi
		;;
	    "QNAP TS-409" | "QNAP TS-41x")
		log_action_msg "System boot completed"
		qcontrol statusled greenon
		if [ "$SOUND_BUZZER" != no ]; then
			qcontrol buzzer short
		fi
		;;
	    *)
		log_warning_msg "qcontrol error: device is not supported"
		;;
	esac
	;;
    stop)
	# TODO: check that daemon is running
	# Change status led to show red
	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")
		log_action_msg "Preparing for shutdown"
		if [ "$SOUND_BUZZER" != no ]; then
			qcontrol buzzer short
		fi
		qcontrol statusled redon
		qcontrol powerled 1hz
		;;
	    "QNAP TS-409" | "QNAP TS-41x")
		log_action_msg "Preparing for shutdown"
		if [ "$SOUND_BUZZER" != no ]; then
			qcontrol buzzer short
		fi
		qcontrol statusled redon
		;;
	    *)
		log_warning_msg "qcontrol error: device is not supported"
		;;
	esac
	;;
    force-stop|restart|force-reload|status|reload)
	;;
    *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|force-stop|restart|force-reload|status}" >&2
	exit 1
	;;
esac

exit 0
