#! /bin/sh
# My cable company reboots my cable box a _lot_ which leaves it off and 
# set to the default -channel 2- when it's powered on. This results in many blank
# recordings in Mythtv as well as lots of profanity. This script checks to see if 
# the box is on, will turn it on and change to the last channel recorded in Mythtv.
# It assumes that you are using /var/log/mythtv/mythbackend.log.  Adjust for your
# own channel change script and blaster name in lirc.conf.  You can run it from cron.
# Written by Peter Hartmann - the color difference part is borrowed from  
# David Bowlers script. 
# Require packages:      
#              ffmpeg netpbm 
# This script may be freely copied and modified


SENSITIVITY=50

# I get a reading of 53 when the box is off and between 7 and 30 when it's on.

#make a directory to work in 

if [ ! -d /tmp/cablebox_on ];
then
mkdir /tmp/cablebox_on
fi
cd /tmp/cablebox_on


#find out it myth is recording and if so, set a variable to the open file

TEST=$(lsof | grep mythba | grep mpg | awk '{print $9}')
if [ -n "$TEST" ]; 
then
RECFILE=$(lsof | grep mythba | grep mpg | awk '{print $9}')
else
RECFILE=NOTRECORDING
fi

echo  $RECFILE

# If we are recording take a sample from the end of the current recording, 
# if we aren't recording get one directly from the tuner card.
 
if [ "$RECFILE" != "NOTRECORDING" ];
then
tail -f  $RECFILE  > myth.mpg &
sleep 7 
kill -9 $!
else
cat /dev/video0 > myth.mpg &
sleep 6 
kill -9 $!
fi

# Take 2 still images from the mpg and convert them to ppm.

ffmpeg -y -i myth.mpg -vframes 1 -ss 00:00:03 -an -vcodec png -f rawvideo -s 320x240 myth1.png
ffmpeg -y -i myth.mpg -vframes 1 -ss 00:00:05 -an -vcodec png -f rawvideo -s 320x240 myth2.png
/usr/bin/pngtopnm myth1.png > myth1.ppm
/usr/bin/pngtopnm myth2.png > myth2.ppm

# Compare. Turn the box on and change to the last channel or do nothing
# if the box is already on.

/usr/bin/pnmpsnr myth1.ppm myth2.ppm> Ycolour 2>&1
Y=`awk '/Y  color/ {print int($5)}' Ycolour`
echo $Y
if [ $Y -gt "$SENSITIVITY" ]
then 
echo turning on cable box
/usr/bin/irsend SEND_ONCE blaster POWER

LAST_CHAN=$( cat /var/log/mythtv/mythbackend.log | grep channel | tail -n 1 | awk  -F channel '{print $2}' | awk '{print $1}')

# channels in the mythbackend.log seem to have 1000 added to them.
CHAN=$(( $LAST_CHAN - 1000 ))
/usr/local/bin/change_chan.sh $CHAN
echo changing to channel $CHAN
fi

rm -rf /tmp/cablebox_on/*


