#!/bin/sh

# ==============================================================================
# BBC iPlayer for Xtreamer Media Player & Streamer
# ==============================================================================
#
# This project allows to watch content brom BBC iPlayer, which is supported
# on Linux by get_iplayer PERL script.
#
# Licence: GNU General Public License v2
# http://www.gnu.org/licenses/gpl.html
#
# Do not remove or change any header comments! Respect our work!
#
# If you are satisfied with my work you can support it with small donation                                                                                                                               
#   https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=SB8WDDAWY5YZE&lc=SI&item_name=xJukebox&item_number=ak5349jgdr&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted	 *
#
# Author: vpeter/misek
#
# ============================================================================== 

# load environment variable
. /tmp/usbmounts/sda1/scripts/BBC-iPlayer/bin/env_setup.sh

# only one instance, except for force
pidfile=/tmp/refresh_cache_tv.pid
if [ -e $pidfile ]; then
	pid=`cat $pidfile`
	if `$MAIN_DIR/bin/busybox kill -0 $pid >/dev/null 2>&1`; then
		echo "Already running"
		if [ "$1" == "force" ]; then
			# kill old instances
			$MAIN_DIR/bin/busybox ps w | grep refresh_cache_tv.sh |grep -v force |grep -v grep | awk '{printf("%s", $1); exit}' |xargs kill
			$MAIN_DIR/bin/busybox ps w | grep get_iplayer_refresh |grep -v grep |awk '{printf("%s", $1); exit}'|xargs kill
		else
			exit 1
		fi
	else
		rm $pidfile
	fi
fi
echo $$ > $pidfile


# last update time (Modify/Change)
TIME_CACHE_OLD=`$STAT -c "%Y" $MAIN_DIR/.get_iplayer/tv.cache`

# refresh programme cache
if [ "$1" == "force" ]; then
	perl $MAIN_DIR/bin/get_iplayer_refresh --type tv --refresh
else
	TIME_NOW=`date +%s`
	DIFF=$((TIME_NOW-TIME_CACHE_OLD))
	
	# more than 4hrs + 30s
	if [ $DIFF -gt 14430 ]; then
		perl $MAIN_DIR/bin/get_iplayer_refresh --type tv
	fi
fi

# refresh sqlite database only if necessary
TIME_CACHE_NEW=`$STAT -c "%Y" $MAIN_DIR/.get_iplayer/tv.cache`

if [ "$TIME_CACHE_NEW" != "$TIME_CACHE_OLD" ]; then
	echo "refreshing sqlite database"
	# delete first line with column names
	sed '1d' $MAIN_DIR/.get_iplayer/tv.cache >tmp.cache1
	# delete \r (0x0D) characters
	tr -d '\r' < tmp.cache1 > tmp.cache
	rm -f tmp.cache1
	
	# import into sqlite database
	$MAIN_DIR/bin/sqlite3 $MAIN_DIR/cache.db < $MAIN_DIR/bin/import_tv_cache.sql 
	#rm -f tmp.cache
fi

rm -f /tmp/force_update.lock
rm -f $pidfile

exit
