#!/bin/sh
# first sh box parser for titannit mfg obi

#SRC=$1
INPUT=$1
TMP=$2
ID=$3
NAME=titan
FILENAME=$NAME
AUTH='aUtzhFRTzuDFa:JNHZbghnjuz'
USERAGENT='Mozilla%2F5.0+%28Windows+NT+6.3%3B+rv%3A36.0%29+Gecko%2F20100101+Firefox%2F36.0'
curlbin="curl -k -s -L --connect-timeout 5 --cookie /mnt/network/cookies --cookie-jar /mnt/network/cookies -A $USERAGENT -u $AUTH"

echo "[epg.sh] $*"

getid()
{
	echo start $INPUT

	rm $TMP/cache.$FILENAME.* > /dev/null 2>&1
	#send: b'POST /EPG/JSON/Login?&T=PC_firefox_75 HTTP/1.1\r\nUser-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:75.0) Gecko/20100101 Firefox/75.0\r\nAccept-Encoding: gzip, deflate, br\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nConnection: keep-alive\r\nHost: api.prod.sngtv.magentatv.de\r\nAccept-Language: de,en-US;q=0.7,en;q=0.3\r\nUpgrade-Insecure-Requests: 1\r\nContent-Length: 47\r\n\r\n'
	#send: b'{"userId": "Guest", "mac": "00:00:00:00:00:00"}'
	data='{"userId": "Guest", "mac": "00:00:00:00:00:00"}'
	echo data $data
	$curlbin -v --data "$data" "https://api.prod.sngtv.magentatv.de/EPG/JSON/Login?&T=PC_firefox_75" > $TMP/cache.$FILENAME.1.data
	#{"enctytoken":"7AF33E6226311C1AD8453850E7D1DF83","encryptiontype":"0002","platformcode":"0200","epgurl":"http://api.prod.sngtv.magentatv.de:33220","version":"MEM V200R008C18SPC806B002","epghttpsurl":"https://api.prod.sngtv.magentatv.de:33227","rootCerAddr":"http://api.prod.sngtv.magentatv.de:33220/EPG/CA/iptv_ca.der","upgAddr4IPTV":"https://slbedifk11100.prod.sngtv.t-online.de:33428/EDS/jsp/upgrade.jsp","upgAddr4OTT":"https://slbedmfk11100.prod.sngtv.t-online.de:33428/EDS/jsp/upgrade.jsp,https://slbedmfk11100.prod.sngtv.t-online.de:33428/EDS/jsp/upgrade.jsp","EPGDomainNameList":[{"key":"3","value":"80.157.246.67"},{"key":"4","value":"80.157.246.67"},{"key":"2","value":"appepmfk20005.prod.sngtv.t-online.de"},{"key":"5","value":"80.157.246.67"},{"key":"6","value":"80.157.246.67"},{"key":"7","value":"80.157.246.67"}],"sam3Para":[{"key":"SAM3ServiceURL","value":"https://accounts.login.idm.telekom.com"},{"key":"OAuthScope","value":"ngtvepg"}]}

	sed 's/#HttpOnly_//g' -i /mnt/network/cookies

	#22222222222222222222222222
	cat $TMP/cache.$FILENAME.1.data | cut -d'"' -f4 > $TMP/cache.$FILENAME.2.token
	token=$(cat $TMP/cache.$FILENAME.2.token)
	echo enctytoken $token
	#send: b'POST /EPG/JSON/Authenticate?SID=firstup&T=PC_firefox_75 HTTP/1.1\r\nUser-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:75.0) Gecko/20100101 Firefox/75.0\r\nAccept-Encoding: gzip, deflate, br\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nConnection: keep-alive\r\nHost: api.prod.sngtv.magentatv.de\r\nAccept-Language: de,en-US;q=0.7,en;q=0.3\r\nUpgrade-Insecure-Requests: 1\r\nCookie: JSESSIONID=H488757FFD954FF24A687BDCD7B808981946AF70F7865334D653A01804187A81F7895A950996F017F31CE301BB55D477E\r\nContent-Length: 249\r\n\r\n'
	#send: b'{"terminalid": "00:00:00:00:00:00", "mac": "00:00:00:00:00:00", "terminaltype": "WEBTV", "utcEnable": "1", "timezone": "UTC", "userType": "3", "terminalvendor": "Unknown", "preSharedKeyID": "PC01P00002", "cnonce": "5c6ff0b9e4e5efb1498e7eaa8f54d9fb"}'
	data="{\"terminalid\": \"00:00:00:00:00:00\", \"mac\": \"00:00:00:00:00:00\", \"terminaltype\": \"WEBTV\", \"utcEnable\": \"1\", \"timezone\": \"UTC\", \"userType\": \"3\", \"terminalvendor\": \"Unknown\", \"preSharedKeyID\": \"PC01P00002\", \"cnonce\": \"${token}\"}"
	echo data $data
	$curlbin -v --data "$data" "https://api.prod.sngtv.magentatv.de/EPG/JSON/Authenticate?SID=firstup&T=PC_firefox_75" > $TMP/cache.$FILENAME.3.data

	sed 's/#HttpOnly_//g' -i /mnt/network/cookies

	#33333333333333333333333333

	#send: b'POST /EPG/JSON/AllChannel?SID=first&T=PC_firefox_75 HTTP/1.1\r\nUser-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:75.0) Gecko/20100101 Firefox/75.0\r\nAccept-Encoding: gzip, deflate, br\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nConnection: keep-alive\r\nX_CSRFToken: 233832ae5bcd4b11d4c4859a6bd4f8ec22c326995b5946e2\r\nHost: api.prod.sngtv.magentatv.de\r\nAccept-Language: de,en-US;q=0.7,en;q=0.3\r\nUpgrade-Insecure-Requests: 1\r\nCookie: CSESSIONID=7CA07B8303911CB779D742FE5D191C14; CSRFSESSION=233832ae5bcd4b11d4c4859a6bd4f8ec22c326995b5946e2; JSESSIONID=EA204EB120FAB20CA1D3173EDFB01117\r\nContent-Length: 364\r\n\r\n'
	#send: b'{"properties": [{"name": "logicalChannel", "include": "/channellist/logicalChannel/contentId,/channellist/logicalChannel/name,/channellist/logicalChannel/pictures/picture/imageType,/channellist/logicalChannel/pictures/picture/href"}], "metaDataVer": "Channel/1.1", "channelNamespace": "2", "filterlist": [{"key": "IsHide", "value": "-1"}], "returnSatChannel": "0"}'
	#"csrfToken":"b0c222408fb035b4117cef73b6dadbfe3c8461c15ace705b",#
	data='{"properties": [{"name": "logicalChannel", "include": "/channellist/logicalChannel/contentId,/channellist/logicalChannel/name,/channellist/logicalChannel/pictures/picture/imageType,/channellist/logicalChannel/pictures/picture/href"}], "metaDataVer": "Channel/1.1", "channelNamespace": "2", "filterlist": [{"key": "IsHide", "value": "-1"}], "returnSatChannel": "0"}'
	echo data $data
	cat $TMP/cache.$FILENAME.3.data | sed -nr 's/.*"csrfToken":"([^"]+)".*/\1/p' > $TMP/cache.$FILENAME.4.xsfrtoken
	#"csrfToken":"
	xsfrtoken=$(cat $TMP/cache.$FILENAME.4.xsfrtoken)
	$curlbin -H "X_CSRFToken: $xsfrtoken" -v --data "$data" "https://api.prod.sngtv.magentatv.de/EPG/JSON/AllChannel?SID=first&T=PC_firefox_75" > $TMP/cache.$FILENAME.5.data
	cat $TMP/cache.$FILENAME.5.data | sed 's/{/\n\n{/g' | sed 's/\\//g' > $TMP/cache.$FILENAME.6.data.cat
	cat $TMP/cache.$FILENAME.5.data | sed 's/{"contentId/\n{"contentId/g' | sed 's/\\//g' > $TMP/cache.$FILENAME.7.data.cat

	sed 's/#HttpOnly_//g' -i /mnt/network/cookies


	#44444444444444444444444444

	#66666666666666666666666666
	#send: b'POST /EPG/JSON/PlayBillList?userContentFilter=241221015&sessionArea=1&SID=ottall&T=PC_firefox_75 HTTP/1.1\r\nUser-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:75.0) Gecko/20100101 Firefox/75.0\r\nAccept-Encoding: gzip, deflate, br\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nConnection: keep-alive\r\nX_CSRFToken: 77d49d0a73a4db615ac9b57c85739c2fba6f60baa4256cae\r\nHost: api.prod.sngtv.magentatv.de\r\nAccept-Language: de,en-US;q=0.7,en;q=0.3\r\nUpgrade-Insecure-Requests: 1\r\nCookie: CSESSIONID=3C32009ED9E3D4D8A782375D93E37B7A; CSRFSESSION=77d49d0a73a4db615ac9b57c85739c2fba6f60baa4256cae; JSESSIONID=7C248D77BD17F8032A8697D5C6DD0030\r\nContent-Length: 372\r\n\r\n'
	#send: b'{"channelid": "5508", "type": "2", "offset": "0", "count": "-1", "isFillProgram": "1", "properties": "[{\\"name\\":\\"playbill\\",\\"include\\":\\"ratingForeignsn,id,channelid,name,subName,starttime,endtime,cast,casts,country,producedate,ratingid,pictures,type,introduce,foreignsn,seriesID,genres,subNum,seasonNum\\"}]", "endtime": "20240408235959", "begintime": "20240401000001"}'
	#data='{"channelid": "5508", "type": "2", "offset": "0", "count": "-1", "isFillProgram": "1", "properties": "[{\\"name\\":\\"playbill\\",\\"include\\":\\"ratingForeignsn,id,channelid,name,subName,starttime,endtime,cast,casts,country,producedate,ratingid,pictures,type,introduce,foreignsn,seriesID,genres,subNum,seasonNum\\"}]", "endtime": "20240408235959", "begintime": "20240401000001"}'
	data='{"channelid": "5508", "type": "2", "offset": "0", "count": "-1", "isFillProgram": "1", "properties": '[{\"name\":\"playbill\",\"include\":\"ratingForeignsn,id,channelid,name,subName,starttime,endtime,cast,casts,country,producedate,ratingid,pictures,type,introduce,foreignsn,seriesID,genres,subNum,seasonNum\"}]', "endtime": "20240408235959", "begintime": "20240401000001"}'
	echo data $data
	$curlbin -H "X_CSRFToken: $xsfrtoken" -v --data "$data" "https://api.prod.sngtv.magentatv.de/EPG/JSON/PlayBillList?userContentFilter=241221015&sessionArea=1&SID=ottall&T=PC_firefox_75" > $TMP/cache.$FILENAME.8.data
	cat $TMP/cache.$FILENAME.8.data | sed 's/{/\n\n{/g' | sed 's/\\//g' > $TMP/cache.$FILENAME.9.data.cat
	cat $TMP/cache.$FILENAME.8.data | sed 's/{"id":/\n{"id":/g' | sed 's/\\//g' > $TMP/cache.$FILENAME.10.data.cat.epg


	sed 's/#HttpOnly_//g' -i /mnt/network/cookies
}

download()
{
	echo start $INPUT
	$curlbin "http://openaaf.dyndns.tv/epg/titan.epg.gz" | gzip -d > $TMP/$FILENAME.epg
}

extract()
{
	echo start $INPUT
	gzip -d $TMP/titan.epg.gz
}

uselocal()
{
	touch /tmp/.epgrunning
	echo start $INPUT
echo /tmp/localhoster/epg/vxparser.sh $TMP
	/tmp/localhoster/epg/vxparser.sh $TMP
	unlink /tmp/.epgrunning
}

convert()
{
	echo start $INPUT
	if [ -e "$TMP/epg.xml.gz" ];then
		cat $TMP/epg.xml.gz | gzip -d | sed -e 's/^[ \t]*//;s/[ \t]*$//g' -e 's/ system="onscreen"//g' -e 's/ lang="de"//g' -e 's/<programme /{programme /' -e 's/<title>/{title}/' -e 's;</title>;{/title};' -e 's/<sub-title>/{sub-title}/' -e 's;</sub-title>;{/sub-title};' -e 's/<desc>/{desc}/' -e 's;</desc>;{/desc}};' -e 's;</programme>;</programme};g' -e '/^ *$/d' | tr '\012' '|' | sed -e 's/{programme/\n{programme/g' | sed -e 's/<director>/Regie: /' -e 's/<director>/, /g' -e 's/<actor>/Darsteller:|/' -e 's/<actor>//g' -e 's/<producer>/Producer: /' -e 's/<producer>/, /g' -e 's/<date>/Jahr: /' -e 's/<date>//g' -e 's/<category>/Genre: /' -e 's/<category>/, /g' -e 's/<country>/Land: /' -e 's/<country>//g' -e 's/<episode-num>/Folge: /' -e 's/<episode-num>//g' -e 's/<rating>/Rating: /' -e 's/Rating: |/Rating: /' -e 's/<rating>//g' -e 's/<\/\?[^>]\+>//g' -e '/^ *$/d' -e 's/|/\\n/g' -e 's/\\n</</g' -e 's/\\n</</g' -e 's/\\n,/,/g' | awk -v NAME=$NAME \
		'
			# BEGIN variable setzen
			BEGIN \
				{
#					print "start"
				}
				/{programme/ \
				{
#					print "$0" $0

					i = index($0, "channel=\"") + 9
		            j = index(substr($0, i), "\"") - 1
		            channel = substr($0, i, j)

					i = index($0, "start=\"") + 7
		            j = index(substr($0, i), "\"") - 1
		            begin = substr($0, i, j)
					begin = mktime(substr(begin, 0, 4) " "substr(begin, 5, 2)" "substr(begin, 7, 2)" "substr(begin, 9, 2)" "substr(begin, 11, 2)" "substr(begin, 13, 2))

					i = index($0, "stop=\"") + 6
		            j = index(substr($0, i), "\"") - 1
		            end = substr($0, i, j)
					end = mktime(substr(end, 0, 4) " "substr(end, 5, 2)" "substr(end, 7, 2)" "substr(end, 9, 2)" "substr(end, 11, 2)" "substr(end, 13, 2))

					if ($0 ~ /{title}/)
					{
	 					i = index($0, "{title}") + 7
				        j = index(substr($0, i), "{") - 1
				        title = substr($0, i, j)
					}
					else
			            title = ""

					if ($0 ~ /{sub-title}/)
					{
						i = index($0, "{sub-title}") + 11
			            j = index(substr($0, i), "{") - 1
			            subtitle = substr($0, i, j)
					}
					else
			            subtitle = ""

					if ($0 ~ /{desc}/)
					{
						i = index($0, "{desc}") + 6
				        j = index(substr($0, i), "{") - 1
				        desc = substr($0, i, j)
					}
					else
			            desc = ""

					i = index($0, "}}") + 2
					j = index(substr($0, i), "</programme") - 1
		            longdesc = substr($0, i, j)
#		            longdesc = substr($0, i, length($0))

					print "<epg channel=\x22" channel "\x22 begin=\x22" begin "\x22 end=\x22" end "\x22 title=\x22" title "\x22 sub-title=\x22" subtitle "\x22 desc=\x22" desc "\x22 longdesc=\x22" longdesc "\x22" 

					next
				}
		# 29. schreibe alles in die list datei
		' >$TMP/$FILENAME.epg
		echo "created $TMP/$FILENAME.epg done"
	else
		echo "error no input file $TMP/epg.xml.gz found"
	fi
	# 30. gebe titan den list namen mit pfad zurueck
#	echo "$TMP/$FILENAME.epg"
#	cat "$TMP/$FILENAME.list"
}

map()
{
	rm -r $TMP > /dev/null 2>&1
	mkdir $TMP > /dev/null 2>&1
	cp /mnt/settings/channel $TMP/channel.org
	cp /mnt/settings/channel $TMP/channel.neu

	#LIST1=$(cat /mnt/settings/channel | grep vavoo)
	#LIST2=$(cat /mnt/settings/channel | grep -n vavoo)
	cat $TMP/channel.org | grep vavoo > $TMP/cache.round1
	cat $TMP/channel.org | grep -v vavoo > $TMP/cache.round2
	#for ROUND1 in $LIST1; do
	while read -u 3 ROUND1; do
#    echo $ROUND1
		channel1=$(echo $ROUND1 | cut -d"#" -f1)
		channel1tid=$(echo $ROUND1 | cut -d"#" -f2)
    echo channel: $channel1
#		channel1neu=$(sed -e 's/ \[.*\]//;s/ (.*)//' <<< "$channel1")
		channel1neu=$(sed -e 's/ [.*]//;s/ (.*)//g' -e 's/ UHD$//' -e 's/ FHD$//' -e 's/ HD$//' -e 's/ HD+$//' -e 's/ BOX$//' -e 's/ BOX1$//' -e 's/ 1+$//' -e 's/ HEVC$//' <<< "$channel1")


#/tmp/localhoster/epg/epg.sh: line 173: syntax error: unexpected redirectio

		foundchannel=$(cat $TMP/channel.org | grep -v vavoo | grep -i "$channel1neu" | head -n1)
		if [ ! -z "$foundchannel" ];then
			name=$(echo $foundchannel | cut -d"#" -f1)
			sid=$(echo $foundchannel | cut -d"#" -f4)
			tid=$(echo $foundchannel | cut -d"#" -f2)

#	echo found channel1 $channel1=$channel2
#    echo $ROUND1
#	echo found name $name
#	echo found sid $sid
#	echo found tid $tid
#echo "###############"
#   echo $ROUND1 | sed 's/#.*#.*//'
#   echo $ROUND1 | sed -re 's/(\s#)"/\1/'
#   echo $ROUND1 | sed -e 's/\(.*\)\#.*/\1/'

			OUT=$(echo $ROUND1 | sed -e 's/\(.*\)\#.*/\1/')$(echo "#$sid,$tid,$channel1tid")

			echo $OUT >> $TMP/channel.tmp
			echo "$sid#$tid" >> $TMP/epgchannel.tmp
			echo "$sid#$tid#$channel1tid" >> $TMP/epgmap.neu

#sed "s;$ROUND1;$OUT;" -i $TMP/channel.neu

			sed "s;$channel1#$channel1tid#.*;;" -i $TMP/channel.neu
			echo $OUT >> $TMP/channel.neu

#exit
		fi

	done 3<$TMP/cache.round1

	cat $TMP/channel.tmp | sort -u > $TMP/channel.tmp.sort
	cat $TMP/channel.neu | sort -u > $TMP/channel.neu.sort
	cat $TMP/epgchannel.tmp | sort -u > $TMP/epgchannel.tmp.sort
	cat $TMP/epgmap.neu | sort -u > $TMP/epgmap.neu.sort
}

case $INPUT in
	getid) $INPUT;;
	convert) $INPUT;;
	download) $INPUT;;
	map) $INPUT;;
	extract) $INPUT;;
	uselocal) $INPUT;;
esac


