#!/bin/sh

#  Copyright (c) 2005 Jacob Meuser <jakemsr@jakemsr.com>
#
#  Permission to use, copy, modify, and distribute this software for any
#  purpose with or without fee is hereby granted, provided that the above
#  copyright notice and this permission notice appear in all copies.
#
#  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
#  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
#  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
#  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
#  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
#  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


: ${RECDIR:=${HOME}/tv}
: ${NORM=ntsc}
: ${CHANSET=nabcst}


function usage
{
	echo "Usage: btv [-vm] [-c channel] [-d directory] [-n norm]"
	echo "          [-r command]"

	exit 1
}


RECCMD="null"
MUTE="no"
V=""
RET=0


args=`getopt c:d:mn:r:v $*` || usage
set -- $args
for i
do
	case "$i"
	in
		-c)
			CHANNEL=$2; shift; shift;;
		-d)
			DIR=$2;     shift; shift;;
		-m)
			MUTE="yes";	   shift;;
		-n)
			NORM=$2;    shift; shift;;
		-r)
			RECCMD=$2;  shift; shift;;
		-v)
			V="$V -v";	   shift;;
		--)
			shift; break;;
	esac
done

if test x"$CHANNEL" != x"" ; then
	tunerctl -q chanset=$CHANSET channel=$CHANNEL
fi

case $RECCMD in
	start)
		if test x"$MUTE" != x"yes" ; then
			tunerctl -q mute=off
		fi
		# mixer settings?
		if test x"$RECDIR" != x"" ; then
			mkdir -p $RECDIR
			cd $RECDIR || exit 1
		fi
		bsdavrec $V -n $NORM -o out.bsdav -p rec.pid 2>rec.log &
		;;
	stop)
		if test x"$RECDIR" != x"" ; then
			cd $RECDIR || exit 1
		fi
		kill -INT `sed 1q rec.pid`
		if test x"$MUTE" != x"yes" ; then
			tunerctl -q mute=on
		fi
		;;
	play)
		if test x"$RECDIR" != x"" ; then
			cd $RECDIR || exit 1
		fi
		xset -dpms
		bsdavplay $V -i out.bsdav
		RET=$?
		xset +dpms
		;;
	clean)
		if test x"$RECDIR" != x"" ; then
			cd $RECDIR || exit 1
		fi
		rm -f rec.pid rec.log out.bsdav
		;;
	null)
		;;
	*)
		usage
		;;
esac

# no recording command, just watching TV
if test x"$RECCMD" = x"null" ; then
	xset -dpms
	if test x"$MUTE" != x"yes" ; then
		tunerctl -q mute=off
	fi
	bktrplay $V -n $NORM
	RET=$?
	if test x"$MUTE" != x"yes" ; then
		tunerctl -q mute=on
	fi
	xset +dpms
fi

exit $RET
