#!/bin/bash

cd $(dirname "${0}")

#
# START USER CONFIGURATION
#
max_delay=18000

tvguide_user="WikiUsername"
tvguide_password="wikipassword"

wgetopts='-q -T 300 -t 5'
wget_params="--http-user=${tvguide_user} --http-passwd=${tvguide_password} ${wgetopts}"

data_dir="/root/.xmltv"

xmltv="${data_dir}/tvguide.xml"
xsl_fix="${data_dir}/xmltv.xsl"
xsl_check="${data_dir}/xmltv_check.xsl"

target="/var/www/localhost/xmltv.xml"
#
# END USER CONFIGURATION
#

# Ensure prerequisites
xsl_proc="xsltproc"
url="http://minnie.tuhs.org/tivo-bin/xmlguide.pl"

[ -d "${data_dir}" ] || mkdir "${data_dir}"

ok=`which ${xsl_proc} | grep "no ${xsl_proc}"`
if [ "${ok}" != "" ]; then
	echo "ERROR: XSL processor (${xsl_proc}) required and not found"
	exit 1
fi

if [ ! -f "${xsl_fix}" ]; then
	echo "ERROR: XSL file (${xsl_fix}) not found - can't process guide data"
	exit 1
fi

if [ ! -f "${xsl_check}" ]; then
	echo "Warning: XSL file (${xsl_check}) not found - no final validation will occur"
fi

# Random sleep
sleep $((RANDOM % ${max_delay}))

# Grab guide - 31 day rolling cache
outfile="${data_dir}/`date +%d`.xml"
ret=`wget ${wget_params} "${url}" -O "${outfile}"`
if [ "${ret}" != "" ]; then
	echo "ERROR: wget failed on ${url}"
	echo "${ret}"
	exit 1
fi

# process output
ret=`$xsl_proc $xsl_fix ${outfile} > ${xmltv}`
if [ "${ret}" != "" ]; then
	echo "ERROR: XMLTV download/process error"
	echo "${ret}"
	exit 1
fi

# verify
if [ -f "${xsl_check}" ]; then
	ret=`$xsl_proc $xsl_check $xmltv > /dev/null`
	if [ "${ret}" != "" ]; then
		echo "ERROR: Can't validate resulting XML"
		echo "${ret}"
		exit 1
	fi
fi

if [ "${target}" != "" ] && [ -d "$(dirname ${target})" ]; then
	cp "${xmltv}" "${target}"
fi

exit 0

