#!/bin/bash 
# ================= record-tv.sh  ==========================
# = copyright 2003 by Greg Watson <gwatson@linuxlogin.com> =
# = GPL2 License                                           =
# = usage record-tv.sh prefix-filename record-time channel =
# = Example:  ./record-tv.sh enterprise 61:00 20           =
# ==========================================================
# Version 0.8
# Last Mod: Wed Jan  7 12:48:15 MST 2004

# Output directory
OUTPUT=$HOME/NFSHOME/vcr
# Streamer location
STREAMER=/usr/bin/streamer
# Alsa Mixer
AMIXER=/usr/bin/amixer
# v4lctl path
V4LCTL=/usr/bin/v4lctl
# Capture Volume to ensure sound is recorded (80%)
CAPTURE_VOLUME=100

# Tvtime settings file for color/brightness/contrast values
TVTIME=$HOME/.tvtime/tvtime.xml

# End of Config
###############

# check if I'm running TV, if so just exit
if [ `ps -C tvtime | grep -c tvtime` -gt 0 ]; then
	echo "TVtime is running, aborting recording."
	exit
fi

# If the filename prefix wasn't given, set it to 'recording'
if [ -z $1 ]; then
	PREFIX="recording"
else
	PREFIX=$1
fi

# if time is blank, record for 30 minutes
if [ -z $2 ]; then
	TIME="30:00"
else
	TIME=$2
fi

if [ ! -z $3 ]; then
	$V4LCTL setchannel $3
fi

# Check for vcr dir
if [ ! -x $OUTPUT ]; then
	mkdir $OUTPUT
fi
	
DATE=`date +%m-%d-%Y-%H:%M`

# Set the AC97 volume to 0 (so we don't hear the sounds)
# Get mixer values first
PLAY_VOL=`$AMIXER cget name='Analog Mix Playback Volume' | grep : | sed 's/^.*=\([^,]*\).*$/\1/'`
CAP_VOL=`$AMIXER cget name='Analog Mix Capture Volume' | grep : | sed 's/^.*=\([^,]*\).*$/\1/'`
# Fix for my card since sometimes it wants to record PCM, which I DON'T Want 
$AMIXER -q cset name='PCM Capture Volume' 0

$AMIXER -q cset name='Analog Mix Playback Volume' 0
# We want to ensure that volume is set (just in case it wasn't before)
$AMIXER -q cset name='Analog Mix Capture Volume' $CAPTURE_VOLUME

# if tvtime.xml is set, then grab settings out of it
if [ -f $TVTIME ]; then
	CONTRAST=`cat ${TVTIME} | grep DefaultContrast | sed 's/^.*value="\([^"]*\).*$/\1/'`
	BRIGHTNESS=`cat ${TVTIME} | grep DefaultBrightness | sed 's/^.*value="\([^"]*\).*$/\1/'`
	COLOR=`cat ${TVTIME} | grep DefaultColour | sed 's/^.*value="\([^"]*\).*$/\1/'`
	HUE=`cat ${TVTIME} | grep DefaultHue | sed 's/^.*value="\([^"]*\).*$/\1/'`

	$V4LCTL bright ${BRIGHTNESS}% color ${COLOR}% contrast ${CONTRAST}% hue ${HUE}%
fi

$STREAMER -p 4 -q -t ${TIME} -r 24 -q -o ${OUTPUT}/${PREFIX}-${DATE}-${TIME}.avi -j 90 -f mjpeg -F mono16

# Sometimes streamer doesn't always re-mute audio, mute it again just to be sure
$V4LCTL volume mute on

# Restore volumes
$AMIXER -q cset name='Analog Mix Playback Volume' $PLAY_VOL
$AMIXER -q cset name='Analog Mix Capture Volume' $CAP_VOL
