#!/bin/sh

# These will be copied while upgrading.
WEBUSER=root
WEBPASS=loeder64
DRTICDIR=""

#
# Changes after this point will be lost after an upgrade
#
VERSION=12
WEBSITE="http://dreambox:dreambox01@flexmenu.shoenix.net/cgi-bin/subtitlev11.cgi"
SCRIPT="$0"
MSGBOX="/var/bin/msgbox"
SHEXEC="/var/bin/shellexec"
INPUT="/var/bin/input"
BOXTYPE="`sed -e'/^type=/!d' -e 's/type=//' /proc/bus/dreambox`"
MENUFILE="/tmp/subtitle.menu"
EPGFILE="/tmp/subtitle.epg"
INCFILE="/tmp/subtitle.inc"
TMPFILE="/tmp/subtitle.tmp"
# Removes all <> enclosed tags
NOTAG='-e s/<[^>]*>//g'
# Removes all &; enclosed escapec characters
NOESC='-e s/&[^;]*;//g'
# Removes all () enclosed occurences except the ones containing numbers
NOBRC='-e s/([^)0-9]*)//g'
# Removes the first newline
NONWL='-e N;s/\n//g'
# Removes tne " characters
NOQU1='-e s/"//g'
# Removes the ' characters
NOQU2="-e s/'//g"
# A commonly used filter
FILTR="$NOTAG $NOESC $NOBRC"


if [ "$DRTICDIR" = "" ]; then
	case "$BOXTYPE" in
		DM7000)	DRTICDIR="/var/tit"
			;;
		DM500)	DRTICDIR="/tmp"
			;;
		*)	DRTICDIR="/etc/tuxbox/Drtic/tit"
			;;
	esac
fi

if [ "$1" = "-debug" ]; then
        set -x
        shift;
        MSGBOX="echo DEBUG: msgbox"
        INPUT="echo DEBUG: input"
        SHEXEC="echo DEBUG: shellexec"
        DEBUG=1
fi

if [ ! -d $DRTICDIR ]; then
	$MSGBOX msg="~cDe DrTic directory bestaat niet! ($DRTICDIR)."
	exit 0;
fi

presexec() {
        while [ true ]; do
        ARG="$1"
        if [ "$ARG" != "" ]; then
                MYPATH="`which $1`"
                RSLT=""
                if [ "$MYPATH" != "" -a -f "$MYPATH" ]; then
                        RSLT="present"
                        if [ -x "$MYPATH" ]; then
                                RSLT="$RSLT and executable"
                        else    RSLT="$RSLT and not executable"
                        fi
                else    RSLT="missing"
                fi
                echo " - $1 ($MYPATH) : $RSLT"
                shift;
        else    break;
        fi
        done
}

runtest() {
        echo "Current config : "
        echo "---------------- "
        echo "VERSION=$VERSION"
        echo "WEBSITE=$WEBSITE"
        echo "PWD=`pwd`"
        echo "SCRIPT=$SCRIPT"
        echo "MSGBOX=$MSGBOX"
        echo "INPUT=$INPUT"
        echo "SHEXEC=$SHEXEC"
        echo "BOXTYPE=$BOXTYPE"
	echo "DRTICDIR=$DRTICDIR"
	echo "WEBUSER=$WEBUSER"
	echo "WEBPASS=$WEBPASS"
        echo "Linux version = `uname -a`"
        if [ -f /etc/Gemini.conf ]; then
                echo "Image type is Gemini"
        fi
        echo " "
        echo "Testing presence of needed binaries:"
        presexec tar touch printf grep sed head tail wget awk $INPUT $MSGBOX $SHEXEC
        echo "Testing connectivity ..."
	wget "$WEBSITE?upgrade" -O /tmp/wget.tmp
        rm -f /tmp/wget.tmp
	echo "Testing EPG get ..."
	wget "http://$WEBUSER:$WEBPASS@localhost/getcurrentepg" -O /tmp/wget.tmp
        rm -f /tmp/wget.tmp
        exit 0;
}

runmenu() {
	echo "MENU=Shoenix Ondertitels (v$VERSION)" > $MENUFILE
	echo "ACTION=&Zoek en Download,($INPUT l='@@@@@@@@@@@@@@@@@@@@@@@' t='Film Titel (of deel)' d=' ' c=25 k=0 f=0 | $SCRIPT getlist),Moment a.u.b. ..." >> $MENUFILE
	echo "ACTION=&Zoek vanuit EPG en Download,($SCRIPT epgmenu),Moment a.u.b. ..." >> $MENUFILE
	echo "ACTION=&Verwijderen,($SCRIPT deletelist ; ret=\$? ; if [ \$ret -eq 0 ]; then $SHEXEC $INCFILE; fi),De lijst wordt gegenereerd ..." >> $MENUFILE
	echo "ACTION=&Script Upgraden,($SCRIPT upgrade),Moment a.u.b. ..." >> $MENUFILE
	echo "ENDMENU" >> $MENUFILE
	exit 0;
}

runepgmenu() {
        echo "MENU=Shoenix Ondertitels EPG (v$VERSION)" > $EPGFILE
        wget -q http://$WEBUSER:$WEBPASS@localhost/getcurrentepg -O - |grep '"event"'|sed -e 's/^.*<span[^>]*>//g' -e 's/<[^>]*>//g' -e 's/[&()*]//g' $NOQU1 $NOQU2|while read epg; do
                echo "ACTION=&$epg,($INPUT l='@@@@@@@@@@@@@@@@@@@@@@@' t='Pas de titel evt. aan' d=\"$epg\" c=25 k=0 f=0 | $SCRIPT getlist),Moment a.u.b. ..." >> $EPGFILE
        done
        echo "ENDMENU" >> $EPGFILE
        $SHEXEC $EPGFILE
        if [ "$DEBUG" != "1" ]; then rm -f $EPGFILE; fi
        exit 0;
}

runinstall() {
	if [ -f "$1" ]; then
		cd $DRTICDIR
		tar xzf $1
		rm -f $1
		$MSGBOX popup="~cDe ondertitels zijn succesvol geinstalleerd."
	else	$MSGBOX popup="~cDe ondertitels zijn NIET geinstalleerd."
	fi
	exit 0;
}

runupgrade() {
	wget -q "$WEBSITE?upgrade" -O /tmp/$$.upgrade
	if [ ! -f /tmp/$$.upgrade -o "`grep '# END OF FILE' /tmp/$$.upgrade`" = "" ]; then
		$MSGBOX popup="~cUpgrade mislukt."
		rm -f /tmp/$$.upgrade
		exit 0;
	fi
	NEWVERSION="`cat /tmp/$$.upgrade|grep '^VERSION='|awk -F = '{print $2}'`"
	if [ ! $NEWVERSION -gt $VERSION ]; then
		$MSGBOX msg="~cScript is al up-to-date (v$VERSION)"
		rm -f /tmp/$$.upgrade
	else	mv -f $SCRIPT $SCRIPT.v$VERSION
		mv -f /tmp/$$.upgrade $SCRIPT
		# Copy the vars from the old script
		head -2 $SCRIPT > /tmp/$$.script
		head -10 $SCRIPT.v$VERSION | grep '^WEBUSER=' >> /tmp/$$.script
		head -10 $SCRIPT.v$VERSION | grep '^WEBPASS=' >> /tmp/$$.script
		head -10 $SCRIPT.v$VERSION | grep '^DRTICDIR=' >> /tmp/$$.script
		tail +2 $SCRIPT |grep -v '^WEBUSER='|grep -v '^WEBPASS='|grep -v '^DRTICDIR=' >> /tmp/$$.script
		mv -f /tmp/$$.script $SCRIPT
		# Set permissions
		chmod 755 $SCRIPT
		$MSGBOX popup="~cScript is ge-update naar versie $NEWVERSION."
	fi
	exit 0;
}

rundeletelist() {
	NUMFILES="`ls -la $DRTICDIR/*_ALL.dtc|wc -l|awk '{print $1}'`"
	if [ "$NUMFILES" = "0" ]; then
		$MSGBOX popup="~cGeen bestanden gevonden"
		exit 1;
	fi
	echo "MENU=Ondertitels Verwijderen" > $INCFILE
	for i in $DRTICDIR/*_ALL.dtc; do
		FILE="`basename $i`"
		PLAIN="`echo $FILE|sed 's/_ALL\.dtc$//g'`"
		TITLE="`echo $PLAIN|sed 's/_/ /g'`"
		echo "ACTION=&$TITLE,($MSGBOX msg='Weet U het zeker?' select='Ja,Nee' default=2; ret=\$? ; if [ \$ret -eq 1 ]; then $SCRIPT delete "$PLAIN"; fi),Wachten a.u.b!" >> $INCFILE
	done
	if [ "$NUMFILES" -gt 1 ]; then
		echo "ACTION=&Allemaal verwijderen,($MSGBOX msg='Weet U het zeker?' select='Ja,Nee' default=2; ret=\$? ; if [ \$ret -eq 1 ]; then $SCRIPT delete ALL; fi),Wachten a.u.b!" >> $INCFILE
	fi
	echo "ENDMENU" >> $INCFILE
	exit 0;
}

rundelete() {
	FILE="$1"
	if [ "$1" != "ALL" ]; then
		rm -f $DRTICDIR/$1_[0-9].dtc $DRTICDIR/$1_[0-9][0-9].dtc $DRTICDIR/$1_ALL.dtc
		cat $INCFILE | grep -v "delete $FILE; fi" > $TMPFILE
		mv -f $TMPFILE $INCFILE
	else	# Delete all
		rm -f $DRTICDIR/*_ALL.dtc $DRTICDIR/*_[0-9].dtc $DRTICDIR/*_[0-9][0-9].dtc $INCFILE
	fi
	COUNT="`cat $INCFILE|grep -v 'delete ALL; fi' |wc -l|awk '{print $1}'`"
	$MSGBOX popup="~cBestanden zijn verwijderd" refresh=2
	if [ "$1" = "ALL" -o $COUNT -lt 3 ]; then
		# Kill the window, it's empty
		PID="`ps -ef|grep deletelist|awk '{print $1}'`"
		kill $PID
		PID="`ps -ef|grep $INCFILE|awk '{print $1}'`"
		kill $PID
	fi
	exit 0;
}

rungetlist() {
	read inp;

	inp="`echo $inp|sed 's/ /%20/g'`"

	if [ -z "$inp" ]; then
		exit 0;
	fi

	wget -q -O $TMPFILE "$WEBSITE?title=$inp"
	#
	# Generate the menu
	#
	if [ "`cat $TMPFILE | grep -- '-1#Invalid_Query'`" != "" ]; then
			$MSGBOX msg="~cOngeldige of lege titel opgegeven.~n~cProbeer opnieuw a.u.b."
			exit 0;
	fi
	if [ "`cat $TMPFILE | grep -- '-3#Incompatible_Format'`" != "" ]; then
			$MSGBOX msg="~cOnbekend formaat.~n~cProbeer opnieuw a.u.b."
			exit 0;
	fi
	if [ ! -s $TMPFILE ]; then
			$MSGBOX msg="~cGeen resultaten voor de titel gevonden.~n~cProbeer opnieuw a.u.b."
			exit 0;
	fi
	echo "MENU=Ondertitels Downloaden" > $INCFILE
	cat $TMPFILE|grep -v -- '-2#Too_Many_Results'|while read line; do
		DBID="`echo $line|awk -F \# '{print $1}'`"
		FILENAME="`echo $line|awk -F \# '{print $2}'`"
		TITLE="`echo $line|awk -F \# '{print $2}'|sed 's/_/ /g'`"
		#
		# Send to output
		#
		if [ "$DBID" != "0" ]; then
			echo "ACTION=&$TITLE,(wget \"$WEBSITE?download=$DBID&filename=$FILENAME\" -O /tmp/$DBID.tar.gz ; $SCRIPT install \"/tmp/$DBID.tar.gz\"),Wachten a.u.b! Wordt gedownload ... " >> $INCFILE
		else	echo "COMMENT=&$TITLE" >> $INCFILE
		fi
	done
	echo "ENDMENU" >> $INCFILE
	if [ "`cat $TMPFILE | grep -- '-2#Too_Many_Results'`" != "" ]; then
		RESULTS="`cat $TMPFILE | grep -- '-2#Too_Many_Results'|awk -F \# '{print $3}'`"
		$MSGBOX popup="~cEr waren teveel resultaten.~n~cAlleen de eerste $RESULTS titels worden getoond."
	fi
	rm -f $TMPFILE
	$SHEXEC $INCFILE
	exit 0;
}

#
# Main, process argument and dispatch
#
case "$1" in
	delete)		rundelete "$2";
			;;
	deletelist)	rundeletelist;
			;;
	upgrade)	runupgrade;
			;;
	install)	runinstall "$2";
			;;
	menu)		runmenu;
			;;
	epgmenu)	runepgmenu;
			;;
	getlist)	rungetlist;
			;;
	test)		runtest;
			;;
	*)	echo "Unknown operand passed. Possibilities : test,upgrade,menu,getlist,delete,deletelist,install"
		;;
esac

#
# END OF FILE

