#!/bin/sh

# stereo
#
# wrapper script to control my Denon stereo with IR

# Copyright (c) 2012 Peter Palfrader
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.


set -e

STATEFILE=/var/run/stereo-state
TIMEOUT=30
DEBUG=0

if [ "$#" -lt 1 ]; then
	echo 2>&1 "Usage: $0 <command>"
	exit 1
fi


if grep -q ON "$STATEFILE"; then
	power=1
else
	power=0
fi

send() {
	irsend set_transmitters 1
	irsend send_once denon "$1"
}
toggle_power() {
	send KEY_POWER
}
force_status_update_off() {
	cat /dev/null > "$STATEFILE"
}
off() {
	if [ "$power" -gt 0 ]; then
		toggle_power
		force_status_update_off
	else
		echo "Already off"
	fi
}
on() {
	if [ "$power" -lt 1 ]; then
		toggle_power
		echo ON > "$STATEFILE"
	else
		echo "Already on"
	fi
}

used() {
	if grep -q RUNNING /proc/asound/card*/*p/*/status; then
		return 0
	else
		return 1
	fi
}

tch() {
	touch "$STATEFILE"
}

case "$1" in
	init)
		cat /dev/null > /var/run/stereo-state
		chgrp plugdev /var/run/stereo-state
		chmod 664 /var/run/stereo-state
		;;
	mute)
		send KEY_MUTE
		tch
		;;
	vol+)
		send KEY_VOLUMEUP
		;;
	vol-)
		send KEY_VOLUMEDOWN
		;;
	off)
		off
		;;
	on)
		on
		;;
	toggle)
		if [ "$power" -gt 0 ]; then
			off
		else
			on
		fi
		;;
	status)
		if [ "$power" -gt 0 ]; then
			echo "on; last used: $(stat -c%y "$STATEFILE")"
		else
			echo off
		fi
		;;
	used)
		if used; then
			exit 0
		else
			exit 1
		fi
		;;
	touch)
		tch
		;;
	# runs out of cron every 5 minutes or so
	#  */5 * * * * bin/stereo off-if-idle
	off-if-idle)
		if [ "$power" -gt 0 ]; then
			if used; then
				tch
				[ $DEBUG -lt 1 ] || echo "in use"
			else
				if find "$STATEFILE" -mmin -"$TIMEOUT" | grep -q .; then
					[ $DEBUG -lt 1 ] || echo "recently used"
				else
					off
				fi
			fi
		else
			[ $DEBUG -lt 1 ] || echo "is off"
		fi
		;;
	force-status-off)
		force_status_update_off
		;;
	*)
		echo >&2 "Unknown command $1"
		exit 1
esac