#!/bin/bash
FILES=/home/hts/epg/epg/*
LOGFILE=/home/hts/xmltvlog/xmltv.log
ABLAGE=/home/hts/epg/epg/
DOWNLOAD=/home/hts/epg/download
EPGFILE=/home/hts/epg/epg.xml
INDEX=/home/hts/epg/index.html
RAWCHANNELS=/home/hts/epg/raw-channels.xml
DIR=/home/hts/epg/
rm $LOGFILE
touch $LOGFILE
echo "Starting script..." >> $LOGFILE
echo "Time: $(date)" >> $LOGFILE
rm $FILES
rm $EPGFILE
cat $RAWCHANNELS > $EPGFILE
echo "Copied channel list into EPG file successfully." >> $LOGFILE
echo "" >> $LOGFILE
echo "Getting file list" >> $LOGFILE
rm $INDEX
wget http://xmltv.xmltv.se/ -P $DIR
rm $DOWNLOAD
grep "\"3sat.de\|\"br-alpha.daserste.de\|\"arte.de\|\"bfs.daserste.de\|\"daserste.de\|\"einsextra.daserste.de\|\"einsfestival.daserste.de\|\"gold.sat1.de\|\"hr.daserste.de\|\"infokanal.zdf.de\|\"kabel1.de\|\"doku.kabel1.de\|\"kika.daserste.de\|\"maxx.prosieben.de\|\"mdr.daserste.de\|\"ndr.daserste.de\|\"neo.zdf.de\|\"nitro.rtl.de\|\"n-tv.de\|\"phoenix.daserste.de\|\"prosieben.de\|\"rbb.daserste.de\|\"rtl.de\|\"rtl2.de\|\"rtlplus.de\|\"sat1.de\|\"sixx.de\|\"super.rtl.de\|\"tele5.de\|\"vox.de\|\"wdr.daserste.de\|\"zdf.de" $INDEX | sed -n -e 's/.*href="\(.*\)">.*/\1/p' | sed -e 's/^/http:\/\/xmltv.xmltv.se\//' > $DOWNLOAD
echo "" >> $LOGFILE
echo "These EPG files will be downloaded now:" >> $LOGFILE
echo "======================================" >> $LOGFILE
cat $DOWNLOAD >> $LOGFILE
echo "======================================" >> $LOGFILE
echo "Starting download..." >> $LOGFILE
echo "Time: $(date)" >> $LOGFILE
wget -i $DOWNLOAD -P $ABLAGE
echo "Done. $(date)" >> $LOGFILE
echo "" >> $LOGFILE
echo "Adding EPG data to EPG file:" >> $LOGFILE
for f in $FILES
do
  echo "Processing $f..." >> $LOGFILE
  sed -i '/<\/tv>/d' $EPGFILE
  sed -n -e '/ <programme/,$p' $f >> $EPGFILE
  rm $f
  echo "OK, left file removed" >> $LOGFILE
  echo "" >> $LOGFILE
done
echo "Integrating EPG file into TV Headend..." >> $LOGFILE
echo "Done." >> $LOGFILE
cat $EPGFILE | socat - UNIX-CONNECT:/home/hts/.hts/tvheadend/epggrab/xmltv.sock
echo "" >> $LOGFILE
echo "EPG Updated successfully." >> $LOGFILE
echo "Time: $(date)" >> $LOGFILE
echo "" >> $LOGFILE
echo "Now cleaning up." >> $LOGFILE
rm $DOWNLOAD
rm $EPGFILE
rm $INDEX