#!/bin/sh

NAME="tvtime-vdr"
DEFAULT="$HOME/.tvtime/$NAME.rc"
FIFO="$HOME/.tvtime/$NAME-$(hostname).fifo"

print() { echo "## $1"; [ x$2 = x ] || exit $2; }
finish() { $TVTIMECMD QUIT >/dev/null 2>&1; }

[ $(ps aux | grep -s $NAME | wc -l) -gt 3 ] && print "$NAME is running" 1

if [ ! -e $DEFAULT ]; then
    [ -e $(dirname $DEFAULT) ] || mkdir -p $(dirname $DEFAULT)
    cat >$DEFAULT << EOF
#
# $HOME/.${NAME}.rc
#
VDR_DBUS_SEND=$(which vdr-dbus-send)
SVDRPSEND=$(which svdrpsend)
TVTIME=$(which tvtime)
TVTIMECMD=$(which tvtime-command)
TVTIME_ARGS="--frequencies=europe --norm=PAL --widescreen --fullscreen --mixer=/dev/null --slave"
MAP=/etc/tvtime/map.txt
EOF
fi

. $DEFAULT

trap finish EXIT

[ -z "$(pidof $TVTIME)" ] || killall -TERM $TVTIME

if [ -z "$(pidof vdr)" ]; then
    sudo /etc/pm/sleep.d/30_vdr resume || print "Can´t start VDR" 1
    sleep 1
fi

if [ ! -e "$FIFO" ]; then
    [ -d $(dirname $FIFO) ] || mkdir -p $(dirname $FIFO) || print "couldn´t create $(dirname $FIFO)" 1
    mkfifo -m 0600 $FIFO || print "couldn´t create $FIFO" 1
fi

[ ! -x "$SVDRPSEND}" ] || SEND="$SVDRPSEND HITK "
[ ! -x "$VDR_DBUS_SEND" ] || SEND="$VDR_DBUS_SEND /Remote remote.HitKey string:"
[ -n "$SEND" ] || print "not found: neither '$VDR_DBUS_SEND' nor '$SVDRPSEND'" 1
[ -x "$TVTIME" ] || print "not found: $TVTIME" 1
[ -x "$TVTIMECMD" ] || print "not found: $TVTIMECMD" 1

while [ x$CMD != xq ] && ! pidof $TVTIME >/dev/null 2>&1; do
    $TVTIME $TVTIME_ARGS 2>/dev/null > $FIFO &
    read CMD < $FIFO
    while pidof $TVTIME >/dev/null 2>&1; do
	[ -n "$CMD" ] || read CMD < $FIFO
	[ -n "$CMD" ] || continue
	[ "$CMD" != "q" ] || break
	[ "$CMD" != "f" ] || $TVTIMECMD TOGGLE_FULLSCREEN >/dev/null 2>&1
	$SEND$(grep ^$CMD $MAP | head -n1 | cut -f2) >/dev/null 2>&1
	unset CMD
    done
done

exit 0
