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

SRC=$1
INPUT=$2
PAGE=$3
NEXT=$4
PAGE2=$5
PARSER=`echo $SRC | tr '/' '\n' | tail -n1 | sed 's/.sh//'`

URL="http://dummy.url"
NAME="LoadM3U"

case $2 in
	init)	;;
	*) 	. /tmp/localhoster/hoster.sh
	   	mkdir $TMP > /dev/null 2>&1
		FILENAME="$PARSER $INPUT $PAGE $NEXT"
	   	FILENAME=$(echo $FILENAME | tr '&' '.' | tr '/' '.' | tr '?' '.' | tr '=' '.' | sed -e 's/\&\+/./g' -e 's#\/\+#.#g' -e 's/\?\+/./g' -e 's/;\+/./g' -e 's/=\+/./g' -e 's/-\+/./g' -e 's/[()]/./g' -e 's/://g' -e 's/\《//g' -e 's/\》//g' -e 's/➾//g' -e 's/ \+/./g' -e 's/\.\+/./g')

		if [ -z "$FILENAME" ]; then FILENAME=none;fi
		PICNAME="$FILENAME"
		SKIP=0
		if [ ! -z "$PAGE2" ] && [ "$PAGE2" == "999" ];then
			SKIP=2
			URL="$PAGE"
		elif [ ! -z "$PAGE2" ] && [ "$PAGE2" == "888" ];then
			SKIP=2
			URL="$PAGE"
			if [ $(portscan 1 127.0.0 4323 0 1 | grep ok | wc -l) == 1 ];then
				URL="http://127.0.0.1:4323/playlist/DE.m3u"
				PAGE=$URL
			fi
		elif [ ! -z "$PAGE" ] && [ "$PAGE" == "$NEXT" ];then
			SKIP=1
			URL="$PAGE"
		elif [ `cat /mnt/config/titan.cfg | grep tithek_loadm3u_url= | wc -l` -eq 1 ];then
			URL=$(cat /mnt/config/titan.cfg | grep "tithek_loadm3u_url=" | sed 's/tithek_loadm3u_url=//g')
            if [ `cat /mnt/config/loadm3uhistory | grep ^"$URL" | wc -l` -eq 0 ];then
    			echo " " >> /mnt/config/loadm3uhistory
                echo "$URL" >> /mnt/config/loadm3uhistory
                sed -e '/^\s*$/' -i /mnt/config/loadm3uhistory
            fi
		else
			if [ ! -e /mnt/config/loadm3uhistory ];then
				touch /mnt/config/loadm3uhistory
			fi

			if [ -e /etc/.oebuild ];then
				PLAYLIST="/mnt/swapextensions/usr/share/xupnpd/playlists"
			else
				PLAYLIST="/mnt/swapextensions/usr/local/share/titan/plugins/network/xupnpd/etc/playlists"
			fi

			if [ ! -e $PLAYLIST ];then
				mkdir -p $PLAYLIST
			fi

			MASK=$(route | grep -v 'default\|Destination\|Kernel' | awk '{ print $1 "00"}' | sed 's/.000//')
			SERVER_PORT=4323
			SERVER_M3UFILE=playlist.m3u
			SERVER_M3UFILE=DE.m3u
			SERVER_IP=127.0.0.1
			SERVER_PATH=playlist

			if [ -e "$PLAYLIST" ];then
				if [ ! -e $TMP/$NAME.plesk.checkservers ];then
					rm $TMP/$NAME.plesk.checkservers
					portscan 1 $MASK $SERVER_PORT 0 255 > $TMP/$NAME.plesk.checkservers

					if [ $(cat $TMP/$NAME.plesk.checkservers | wc -l) != 0 ];then
					    URL="$PLAYLIST"
#						rm $PLAYLIST/*\ \(Vavoo\)\ \(*\)\ playlist.m3u
						rm $PLAYLIST/*\ \(Vavoo\)\ \(*\)\ *.m3u

						while read -u 3 ROUND; do
							SERVER_IP=$(echo $ROUND | cut -d " " -f1)
							SERVER_PORT=$(echo $ROUND | awk -F"[()]" '{print $2}')
							LOCAL_M3UFILE=$(echo $ROUND | sed 's, , (Vavoo) ,' | sed "s,) ok,) $SERVER_M3UFILE,")
							wget http://$SERVER_IP:$SERVER_PORT/$SERVER_PATH/$SERVER_M3UFILE -O "$PLAYLIST/$LOCAL_M3UFILE"
#crash test 1 start
#rm "$PLAYLIST/$LOCAL_M3UFILE"
#touch "$PLAYLIST/$LOCAL_M3UFILE"
#crash test 1 end	
						done 3<$TMP/$NAME.plesk.checkservers
					fi
				elif [ $(cat $TMP/$NAME.plesk.checkservers | wc -l) != 0 ];then
				    URL="$PLAYLIST"
				fi

				if [ ! -e $TMP/$NAME.vxparser.checkservers ];then
					SERVER_PORT=8080
					SERVER_IP=127.0.0.1

					rm $TMP/$NAME.vxparser.checkservers
					portscan 1 $MASK $SERVER_PORT 0 255 > $TMP/$NAME.vxparser.checkservers

					if [ $(cat $TMP/$NAME.vxparser.checkservers | wc -l) != 0 ];then
						URL="$PLAYLIST"

						while read -u 3 ROUND; do
							SERVER_IP=$(echo $ROUND | cut -d " " -f1)
							SERVER_PORT=$(echo $ROUND | awk -F"[()]" '{print $2}')

							rm $PLAYLIST/*\ \(Vxparser*\)\ \(*\)\ *.m3u

							SERVER_M3UFILE="tv_channels.m3u"
#							SERVER_PATH="get.php?username=*&password=*&type=m3u_plus&output=hls"
							SERVER_PATH="get.php?username=user&password=pass&type=m3u_plus&output=hls"
							LOCAL_M3UFILE=$(echo $ROUND | sed "s, , (Vxparser) ," | sed "s,) ok,) $SERVER_M3UFILE,")
							wget http://$SERVER_IP:$SERVER_PORT/$SERVER_PATH -O "$PLAYLIST/$LOCAL_M3UFILE"

							if [ ! -e $TMP/$NAME.vxparser.checkplaylists.$SERVER_IP ];then
								$curlbin2 http://$SERVER_IP:$SERVER_PORT | sed 's/<a href/\n<a href/g' | sed -nr 's/.*a href="([^"]+)".*/\1/p' > $TMP/$NAME.vxparser.checkplaylists.$SERVER_IP
							fi

							while read -u 3 ROUND1; do
								SERVER_M3UFILE=$ROUND1
								LOCAL_M3UFILE=$(echo $ROUND | sed "s, , (Vxparser) ," | sed "s,) ok,) $SERVER_M3UFILE," | sed 's/.m3u8/.m3u/')
								if [ "$ROUND1" != "epg.xml.gz" ];then
#									if [ ! -e "$PLAYLIST/$LOCAL_M3UFILE" ];then
#									rm $PLAYLIST/*\ \(Vxparser*\)\ \(*\)\ $ROUND1
									wget http://$SERVER_IP:$SERVER_PORT/$SERVER_M3UFILE -O "$PLAYLIST/$LOCAL_M3UFILE"								
#									fi
								fi
							done 3<$TMP/$NAME.vxparser.checkplaylists.$SERVER_IP

						done 3<$TMP/$NAME.vxparser.checkservers
					fi
				elif [ $(cat $TMP/$NAME.vxparser.checkservers | wc -l) != 0 ];then
				    URL="$PLAYLIST"
				fi
			fi

			if [ "$URL" == "$PLAYLIST" ];then
			    URL="$PLAYLIST"
			elif [ $(portscan 1 127.0.0 4323 0 1 | grep ok | wc -l) == 1 ];then
				URL="http://127.0.0.1:4323/playlist/DE.m3u"
				PAGE=$URL
		    else
				URL="http://dummy.url"
			fi
#crash test 2 start
#URL=/mnt/swapextensions/usr/share/xupnpd/playlists/file_darf_nicht_existieren.m3u
#crash test 2 end
		fi

		if [ `cat /mnt/config/titan.cfg | grep tithek_servicebouquets_autoupdate_epgtype=1 | wc -l` -eq 1 ];then
			EPGTYPE=1
		elif [ `cat /mnt/config/titan.cfg | grep tithek_servicebouquets_autoupdate_epgtype=2 | wc -l` -eq 1 ];then
			EPGTYPE=2
		else
			EPGTYPE=0
		fi

		LIVE=0
		;;
esac

if [ `echo $SRC | grep ^"/mnt/parser" | wc -l` -gt 0 ];then
	TYPE="$SRC - Shell script"
elif [ `echo $SRC | grep ^"/var/swap" | wc -l` -gt 0 ];then
	TYPE="Swap - Shell script"
elif [ `echo $SRC | grep ^"/mnt/swapextensions" | wc -l` -gt 0 ];then
	TYPE="Mnt - Shell script"
else
	TYPE="Flash - Shell script"
fi

init()
{
	rm -rf $TMP > /dev/null 2>&1
	echo "$NAME ($TYPE)#$SRC $SRC mainmenu#http://openaaf.dyndns.tv/mediathek/menu/$PARSER.jpg#$PARSER.jpg#TiThek#66"
}

mainmenu()
{
    if [ "$URL" == "http://dummy.url" ];then
    	echo "Extensions > Install > Network > Vavoo##http://openaaf.dyndns.tv/mediathek/menu/category.jpg#category.jpg#$NAME#0" >$TMP/$FILENAME.list
    	echo "Extensions > List > Vavoo > activate and set autostart > y##http://openaaf.dyndns.tv/mediathek/menu/category.jpg#category.jpg#$NAME#0" >>$TMP/$FILENAME.list
    	echo "-------------------------------------------##http://openaaf.dyndns.tv/mediathek/menu/category.jpg#category.jpg#$NAME#0" >>$TMP/$FILENAME.list
    	echo "Optional:##http://openaaf.dyndns.tv/mediathek/menu/category.jpg#category.jpg#$NAME#0" >>$TMP/$FILENAME.list
    	echo "Extensions > Install > Network > Xupnpd##http://openaaf.dyndns.tv/mediathek/menu/category.jpg#category.jpg#$NAME#0" >>$TMP/$FILENAME.list
    	echo "-------------------------------------------##http://openaaf.dyndns.tv/mediathek/menu/category.jpg#category.jpg#$NAME#0" >>$TMP/$FILENAME.list
    	echo "Or Add Your private WebUrl or local Dir from m3u file in##http://openaaf.dyndns.tv/mediathek/menu/category.jpg#category.jpg#$NAME#0" >>$TMP/$FILENAME.list
    	echo "Tithek > Settings (Menu) > LoadM3U (IpTV) Url##http://openaaf.dyndns.tv/mediathek/menu/category.jpg#category.jpg#$NAME#0" >>$TMP/$FILENAME.list
    	echo "-------------------------------------------##http://openaaf.dyndns.tv/mediathek/menu/category.jpg#category.jpg#$NAME#0" >>$TMP/$FILENAME.list
    	echo "Or press here and open Your WebUrl directly##http://openaaf.dyndns.tv/mediathek/menu/category.jpg#category.jpg#$NAME#113" >>$TMP/$FILENAME.list
    	echo "-------------------------------------------##http://openaaf.dyndns.tv/mediathek/menu/category.jpg#category.jpg#$NAME#0" >>$TMP/$FILENAME.list
    else
    	echo "Category#$SRC $SRC category '$URL' 1#http://openaaf.dyndns.tv/mediathek/menu/category.jpg#category.jpg#$NAME#0" >$TMP/$FILENAME.list
     	echo "Suchen#$SRC $SRC search 'http://127.0.0.1:4323/playlist/DE.m3u' '%search%' 888#http://openaaf.dyndns.tv/mediathek/menu/search.jpg#search.jpg#$NAME#112" >>$TMP/$FILENAME.list
#     	echo "Suchen#$SRC $SRC search '$URL' '%search%' 888#http://openaaf.dyndns.tv/mediathek/menu/search.jpg#search.jpg#$NAME#112" >>$TMP/$FILENAME.list
     	echo "Auswahl#$SRC $SRC search '%search%' '%search%' 999#http://openaaf.dyndns.tv/mediathek/menu/search.jpg#search.jpg#$NAME#113" >>$TMP/$FILENAME.list
    fi

	echo "$TMP/$FILENAME.list"
}

getepg()
{
		if [ "$EPGTYPE" == "1" ];then
			/tmp/localhoster/epg/epg.sh map /tmp/epg
			cp /mnt/settings/epgchannel /tmp/epg/epgchannel_old
			echo " " >> /tmp/epg/epgchannel_old
			cat /tmp/epg/epgchannel.tmp.sort >> /tmp/epg/epgchannel_old
#			cat /tmp/epg/epgchannel_old | sort -u | sed '/^[[:space:]]*$/d' > /mnt/settings/epgchannel
#			cat /tmp/epg/epgchannel_old | sort -u | sed '/^\s*$/d' > /mnt/settings/epgchannel
			cat /tmp/epg/epgchannel_old | sort -u | awk '!/^[ \t]*$/' > /mnt/settings/epgchannel
		fi
		if [ "$EPGTYPE" == "2" ];then
			$curlbin3 https://raw.githubusercontent.com/Mastaaa1987/vxparser/refs/heads/main/vxparser/helper/sql.py > $TMP/vavoo.sql
		fi
}

category()
{
#needed without write URL to titan.cfg
#    if [ "$PAGE" == "$NEXT" ];then
#        URL=$PAGE
#    fi
#echo 000 PAGE $PAGE

#echo 000 URL $URL

    rm "$TMP/$FILENAME.list"
    if [ ! -e "$TMP/$FILENAME.list" ]; then
#		if [ ! -z "$PAGE" ];then
#			URL=$PAGE
#		fi
#echo 111 URL $URL
        if [ $(echo "$URL" | grep ^/ | wc -l) -eq 1 ] && [ "$NEXT" != "skip" ];then
#echo 222 URL $URL

            if [ $(echo "$URL" | awk '{ split($0, a, ".");print a[length(a)]}') == "m3u" ];then
#echo 333 URL $URL

		        TITLE=`echo $URL | sed 's/.m3u//' | awk '{ split($0, a, "/");print a[length(a)]}'`
		        filename=`echo $TITLE`
		        echo "$TITLE#$SRC $SRC search '$URL' '$TITLE' 1#http://openaaf.dyndns.tv/mediathek/menu/$filename.jpg#$filename.jpg#$NAME#0" >> $TMP/$FILENAME.list
            else
#echo 444 URL $URL

                ls -1 "$URL" > $TMP/cache.$FILENAME.1
                while read -u 3 ROUND; do
		            TITLE=`echo $ROUND | sed 's/.m3u//'`
		            filename=`echo $TITLE`
#			        if [ $(echo $TITLE | grep " (Vavoo) (" | wc -l) == "1" ] ;then
			        if [ $(cat "$URL/$ROUND" | grep "group-title=" | wc -l) != 0 ] ;then
#echo 444ok URL $URL

#						TMPURL="http://"$(echo "$ROUND" | sed 's,-(Vavoo)-(,:,' | sed 's,)-,/,')
#			            echo "$TITLE#$SRC $SRC category '$TMPURL'#http://openaaf.dyndns.tv/mediathek/menu/$filename.jpg#$filename.jpg#$NAME#0" >> $TMP/$FILENAME.list
			            echo "$TITLE#$SRC $SRC category '$URL/$ROUND' 'skip'#http://openaaf.dyndns.tv/mediathek/menu/$filename.jpg#$filename.jpg#$NAME#0" >> $TMP/$FILENAME.list

##echo 555 URL $URL
#
					else
#echo 444NOTok URL $URL
##echo 666 URL $URL

			            echo "$TITLE#$SRC $SRC search '$URL/$ROUND' '$TITLE' 1#http://openaaf.dyndns.tv/mediathek/menu/$filename.jpg#$filename.jpg#$NAME#0" >> $TMP/$FILENAME.list
					fi
        		done 3<$TMP/cache.$FILENAME.1
            fi
        else
#		    if [ $(echo "$PAGE" | grep ^/ | wc -l) -eq 1 ];then
#	#        if [ "$PAGE" == "$URL" ];then
#				CMD="cat '$PAGE'"
#		    else
#		        CMD="$curlbin -o - $URL"
#		    fi
		    if [ $(echo "$PAGE" | grep ^/ | wc -l) -eq 1 ];then
	#        if [ "$PAGE" == "$URL" ];then
	#echo 333
	#		    CMD="cat '''$PAGE'''"
				CMD="cat"
				CMDARGS="$PAGE"
		    else
	#echo 444
	#            CMD="$curlbin -o - '$URL'"
				CMD="$curlbin"
				CMDARGS="$URL"
		    fi

#echo 1URL $URL
#echo 1PAGE $PAGE
#echo 1NEXT $NEXT
#echo 1CMD $CMD
#echo 1SKIP $SKIP
		    $CMD "$CMDARGS" | awk -v TEST=$TEST -v TMP=$TMP -v FILENAME=$FILENAME -v SRC=$SRC -v URL=$URL -v PAGE="$PAGE" -v NAME=$NAME -v PICNAME=$PICNAME -v LIVE=$LIVE -v SKIP=$SKIP \
		    '
			    BEGIN \
			    {
				    suche = 1
				    newpage = ""
				    piccount = 0
			    }
                /#EXTINF/ \
			    {
				    if (suche == 1)
				    {
					    if ($0 ~ /group-title=/)
					    {
						    i = index($0, "group-title=\"") + 13
			                j = index(substr($0, i), "\"") - 1
			                title = substr($0, i, j)
							gsub(" \\\\u27be ", " ", title)
					    }
					    else
					    {
                            #EXTINF:-1,DE: ARTE
#						    i = index($0, ":-1,") + 4
#						    title = substr($0, i, length($0) - 1)
                            split($0, a, ",")
                            tag = a[length(a)]
                            title = tag
							gsub(" \\\\u27be ", " ", title)

#                            if (title ~ /:/)
#                            {
#                                split(title, b, ":")
#                                tag2 = b[length(b)]
#                                tag3 = b[1]
#                                gsub(/^ /, "", tag3)
#
#                                title = tag2 " (" tag3 ")"
#                            }

						    found = 2
						    next
					    }
					    
    #	            	gsub("<0xe2><0xad><0x90><0xef><0xb8><0x8f>", "", title)
	                	gsub("⭐️", "", title)

					    picname = tolower(title)

                        if ($0 ~ /tvg-logo=/)
                        {
					        i = index($0, "tvg-logo=\"") + 10
        	                j = index(substr($0, i), "\"") - 1
           	                pic = substr($0, i, j)
                        }

				        if ( pic == "" )
                        {
        	            	gsub(" ", ".", picname)
					        pic = "http://openaaf.dyndns.tv/mediathek/menu/" picname ".jpg"
                        }

                        if (pic ~ /.png/)
                            picext = "png"
                        else
                            picext = "jpg"

						titlenext = title
						gsub(/\(/, "\\\x28", titlenext)
						gsub(/\)/, "\\\x29", titlenext)

					    if (++dup[title] == 1 && title != "")
					    {
                            titletmp = titletmp title
							if(SKIP == 2)
							    print title "#" SRC " " SRC " search \x27" PAGE "\x27 \x27" title "\x27 999#" pic "#" PICNAME "." picname ".jpg#" NAME "#0"
							else
							    print title "#" SRC " " SRC " search \x27" PAGE "\x27 \x27" title "\x27#" pic "#" PICNAME "." picname ".jpg#" NAME "#0"
#						    print title "#" SRC " " SRC " search \x27" PAGE "\x27 \x27" titlenext "\x27#" pic "#" PICNAME "." picname ".jpg#" NAME "#0"
                        }
					    newpage = ""
					    title = ""
					    picname = ""
					    pic = ""
					    next
				    }
			    }
                /^http/ \
			    {
                    if (found == 2)
                    {
#	                    newpage = substr($0, 1, length($0) - 1)
						if ($0 ~ /\r/ || $0 ~ /\n/)
			                newpage = substr($0, 1, length($0) - 1)
						else
			                newpage = substr($0, 1, length($0))

				        if (title != "" && title !~ "= = =")
				        {
					        piccount += 1
							if(LIVE == "1")
						        print title "#" newpage "&livemode=1#" pic "#" PICNAME "." picname "." picext "#" NAME "#2"
							else
						        print title "#" newpage "#" pic "#" PICNAME "." picname "." picext "#" NAME "#2"
				        }
				        
				        newpage = ""
				        title = ""
				        picname = ""
				        pic = ""
                        found = 0
				        next
				    }
			    }
                /^rtmp/ \
			    {
                    if (found == 2)
                    {
#						if ($0 ~ /\n/)
#		                    newpage = substr($0, 1, length($0) - 1)
#						else
##		                    newpage = substr($0, 1, length($0))
	#                    newpage = substr($0, 1, length($0) - 1)
						if ($0 ~ /\r/ || $0 ~ /\n/)
			                newpage = substr($0, 1, length($0) - 1)
						else
			                newpage = substr($0, 1, length($0))

				        if (title != "" && title !~ "= = =")
				        {
					        piccount += 1
					        print title "#" newpage "#" pic "#" PICNAME "." picname "." picext "#" NAME "#2"
				        }
				        
				        newpage = ""
				        title = ""
				        picname = ""
				        pic = ""
                        found = 0
				        next
				    }
			    }
		    ' >$TMP/$FILENAME.list
        fi
	fi

    echo $TMP/$FILENAME.list
}

#sh4 error
#/tmp/localparser/vavoo.sh: line 474: shuf: not found
#awk: bad regex '+[)]+': Invalid preceding regular expression

search()
{
#    if [ $(echo "$URL" | grep ^/ | wc -l) -eq 1 ] && [ -d "$URL" ];then
#        exit
#    fi


#echo PAGE $PAGE
#echo NEXT $NEXT
#echo URL $URL

    if [ "$PAGE" == "$NEXT" ];then
#echo 11
#        if [ `cat /mnt/config/titan.cfg | grep "tithek_loadm3u_url=" | wc -l` -eq 0 ];then
##echo " " >> /mnt/config/titan.cfg
#            echo -en "\ntithek_loadm3u_url=$PAGE" >> /mnt/config/titan.cfg
#            sed -e '/^\s*$/' -i /mnt/config/titan.cfg
#        else
#            sed "s#tithek_loadm3u_url=.*#tithek_loadm3u_url=$PAGE#g" -i /mnt/config/titan.cfg
#        fi
##echo 22
#echo $SRC $SRC category "$PAGE" "$NEXT" 1
        $SRC $SRC category "$PAGE" "$NEXT" 999
        exit
    fi
    echo 3 > /proc/sys/vm/drop_caches

    rm "$TMP/$FILENAME.list"
#    NEXT=$(echo $NEXT | tr '+' ' ')

#    ADD2CHANNEL=2

    ADD2CHANNEL=0
    if [ ! -z "$1" ];then 
        ADD2CHANNEL=$1
        remove "$NEXT"
        rm /mnt/settings/bouquets.tithek.autoupdate."$NAME"."$NEXT".tv.* > /dev/null 2>&1

        if [ ! -e /tmp/settings ];then mkdir /tmp/settings; fi
        if [ -e /mnt/settings/bouquets.tithek.autoupdate."$NAME"."$NEXT".tv ];then
            echo "LIST=$(cat /mnt/settings/bouquets.tithek.autoupdate."$NAME"."$NEXT".tv | sed 's/0#/#/g' | tr '\n' '#' | sed 's/##/#\\|#/g' | sed "s/^#/'/" | sed -e "s/#$/'/g")" >$TMP/$FILENAME.cmd.list
            echo "cat /mnt/settings/channel | grep -v \$LIST >> /tmp/settings/channel.tmp" >> $TMP/$FILENAME.cmd.list
            echo "cp '/mnt/settings/bouquets.tithek.autoupdate."$NAME"."$NEXT".tv' '/tmp/settings/bouquets.tithek.autoupdate."$NAME"."$NEXT".tv.org'" >> $TMP/$FILENAME.cmd.list
        else
            echo "cp /mnt/settings/channel /tmp/settings/channel.tmp" > $TMP/$FILENAME.cmd.list
        fi
		getepg
    fi

#echo 111
	if [ ! -e "$TMP/$FILENAME.list" ]; then
#echo 222
        if [ $(echo "$PAGE" | grep ^/ | wc -l) -eq 1 ];then
#        if [ "$PAGE" == "$URL" ];then
#echo 333
#		    CMD="cat '''$PAGE'''"
		    CMD="cat"
			CMDARGS="$PAGE"
#			NEXT="$(echo "$NEXT" | sed 's/\+//')"
#			NEXT="$(echo "$NEXT" | tr -d '+')"
        else
#echo 444
#            CMD="$curlbin -o - '$URL'"
		    CMD="$curlbin"
			CMDARGS="$URL"
        fi
#echo 555
#echo URL $URL
#echo PAGE $PAGE
#echo NEXT $NEXT
#echo CMD $CMD
#echo CMDARGS $CMDARGS
#echo SKIP $SKIP

#        $CMD
#        $CMD "$CMDARGS" | sed 's/\(\.[A-Za-z]\)/(\1)/g' | sed 's/ \\u27be / /g' | awk -v ADD2CHANNEL=$ADD2CHANNEL -v NEXT="$NEXT" -v TMP=$TMP -v FILENAME=$FILENAME -v SRC=$SRC -v URL=$URL -v PAGE="$PAGE" -v NAME=$NAME -v PICNAME=$PICNAME -v TMP=$TMP -v EPGTYPE=$EPGTYPE -v ARCH=$ARCH -v LIVE=$LIVE -v BCBIN=$BCBIN \
        $CMD "$CMDARGS" | sed 's/ \\u27be / /g' | awk -v ADD2CHANNEL=$ADD2CHANNEL -v NEXT="$NEXT" -v TMP=$TMP -v FILENAME=$FILENAME -v SRC=$SRC -v URL=$URL -v PAGE="$PAGE" -v NAME=$NAME -v PICNAME=$PICNAME -v TMP=$TMP -v EPGTYPE=$EPGTYPE -v ARCH=$ARCH -v LIVE=$LIVE -v BCBIN=$BCBIN \
	    '
		    BEGIN \
		    {
			    found = 0
			    newpage = ""
			    piccount = 0

                if(ADD2CHANNEL != 0)
                {
                    cmd = cmd "cp -a /mnt/settings/channel /tmp/settings/channel.org\n"
#                    cmd = cmd "cp -a /tmp/settings/channel.org /tmp/settings/channel.tmp\n"
                    cmd = cmd "cp -a /mnt/settings/transponder /tmp/settings/transponder.org\n"
                    cmd = cmd "cp -a /tmp/settings/transponder.org /tmp/settings/transponder.tmp\n"
                    cmd = cmd "cp -a /mnt/settings/satellites /tmp/settings/satellites.org\n"
                    cmd = cmd "cp -a /tmp/settings/satellites.org /tmp/settings/satellites.tmp\n"
                    cmd = cmd "cp -a /mnt/settings/bouquets.cfg /tmp/settings/bouquets.cfg.org\n"
                    cmd = cmd "cp -a /tmp/settings/bouquets.cfg.org /tmp/settings/bouquets.cfg.tmp\n"
                    cmd2 = "sed "
                }

		    }
            /#EXTINF/ \
		    {
#print "1 found=" found " PAGE=" PAGE " NEXT=" NEXT " $0=" $0

                IGNORECASE=1;

# sh4 not working old
#                if ($0 ~ NEXT || PAGE ~ /^[/]/)
# sh4 working old
#                if ($0 ~ NEXT || PAGE ~ /^[\/]/)
# working test
#                if ($0 ~ "Germany \\\x28DE\\\x29" || PAGE ~ /^[\/]/)
# working 1
#				 if ($0 ~ /tvg-logo=/)
#				 {
#				 	i = index($0, "group-title=\"") + 13
#				 	j = index(substr($0, i), "\"") - 1
#				 	searchtitle = substr($0, i, j)
#				 }
#
#				 gsub(/\(/, "\\\x28", searchtitle)
#				 gsub(/\)/, "\\\x29", searchtitle)
#                if (searchtitle == tmpnext || PAGE ~ /^[\/]/)

				tmpnext = NEXT
				gsub(/\(/, "\\\x28", tmpnext)
				gsub(/\)/, "\\\x29", tmpnext)
				gsub(/[[:space:]]+$/, "", tmpnext)

###gsub("(&)", "\\\\\\&", newpage3)
#print "tmpnext1", tmpnext
#				gsub("\u002b", "", tmpnext)
#				gsub("\\\\u002b", "", tmpnext)
#				gsub("HD \\\\u002b", "HD", tmpnext)
#gsub("(+)", "\\\\\\+", tmpnext)
#print "tmpnext2", tmpnext
#print "found", found
#print $0


#				if ($0 ~ tmpnext || PAGE ~ /^[\/]/)
#				if ($0 ~ tmpnext && PAGE ~ /-\(Vavoo\)-/)
#				if ($0 ~ tmpnext && PAGE ~ /-\(Vavoo\)-/ || (PAGE ~ /^[\/]/ && PAGE !~ /-\(Vavoo\)-/))
#				if ($0 ~ tmpnext || (PAGE ~ /^[\/]/ && PAGE !~ /-\(Vavoo\)-/))
###				if ($0 ~ tmpnext || (PAGE ~ /^[\/]/ && PAGE !~ / \(Vavoo\) \(/))
#				if ($0 ~ tmpnext || (PAGE ~ /^[\/]/ && $0 ~ /group-title=/)
#				if ($0 ~ /group-title=/)
#					print "eeeeeeeeeeeeeeeeee"

#				if ($0 ~ tmpnext || (PAGE ~ /^[\/]/ && (PAGE !~ /Vavoo/ || PAGE !~ /NameInDerM3u/ )))
#				if ($0 ~ tmpnext)
###				if ($0 ~ tmpnext || (PAGE ~ /^[\/]/ && (PAGE !~ /Vavoo/ && PAGE !~ /NameInDerM3u/ )))
				if ($0 ~ tmpnext || (PAGE ~ /^[\/]/ && $0 !~ /group-title=/))
				{
#print $0
#print "found2", found

			        if (found == 0)
			        {
#print "found3", found

					    if ($0 ~ /tvg-name=/)
					    {
#print "found4", found

					        i = index($0, "tvg-name=\"") + 10
		                    j = index(substr($0, i), "\"") - 1
       	                    title = substr($0, i, j)
#                            gsub(/ /, "", title)
#print "title5", title
                            if (title ~ /:/)
                            {
                                split(title, b, ":")
                                tag2 = b[length(b)]
                                tag3 = b[1]
#                                gsub(/^ /, "", tag3)
								gsub(/^[ \t]+/, "", tag2)
								gsub(/^[ \t]+/, "", tag3)

                                title = tag2 " (" tag3 ")"
#print "title5", title

                            }
                        }
                        else
                        {
                            #EXTINF:-1,DE: ARTE
                            split($0, a, ",")
                            tag = a[length(a)]
                            title = tag
#print "title6", title
                            if (title ~ /:/)
                            {
                                split(title, b, ":")
                                tag2 = b[length(b)]
                                tag3 = b[1]
#                                gsub(/^ /, "", tag3)
								gsub(/^[ \t]+/, "", tag2)
								gsub(/^[ \t]+/, "", tag3)
                                title = tag2 " (" tag3 ")"
#print "title7", title
                            }
                        }
				        picname = tolower(title)

                        gsub(/^[(]+/, "", picname)

                    	gsub(/ FHD/, " ", picname)
                    	gsub(/ HD\+/, " ", picname)
                    	gsub(/ HD/, " ", picname)
                    	gsub(/ RAW/, " ", picname)
                    	gsub(/ HEVC/, " ", picname)
                        gsub(/\(.*\)/, "", picname)
                    	gsub(/\+/, "", picname)
                    	gsub(/\//, " ", picname)
#sh4 error
#                        gsub(/+[)]+/, "", picname)
                        gsub(/\+[)]\+/, "", picname)

                        gsub(/^[ \t]+/, "", picname)
                        gsub(/[ \t]+$/, "", picname)
                        gsub(/\t+/, "", picname)

                        gsub(/^[ ]+/, "", picname)
                        gsub(/[ ]+$/, "", picname)
                        gsub(/ +/, "", picname)

                        if ($0 ~ /tvg-logo=/)
                        {
    					    i = index($0, "tvg-logo=\"") + 10
        	                j = index(substr($0, i), "\"") - 1
           	                pic = substr($0, i, j)
                        }

				        if ( pic == "" )
					        pic = "http://openaaf.dyndns.tv/mediathek/menu/" picname ".jpg"

                        if (pic ~ /.png/)
                            picext = "png"
                        else
                            picext = "jpg"

                        found = 1
				        next
                    }
			    }
            }
            /^http/ \
		    {
#print "2 found=" found " PAGE=" PAGE " NEXT=" NEXT " $0=" $0
                if (found == 2)
                {
#                    newpage = substr($0, 1, length($0) - 1)
					if ($0 ~ /\r/ || $0 ~ /\n/)
	                    newpage = substr($0, 1, length($0) - 1)
					else
	                    newpage = substr($0, 1, length($0))

			        if (title != "" && title !~ "= = =")
			        {
				        piccount += 1

						if(LIVE == "1")
					        print title "#" newpage "&livemode=1#" pic "#" PICNAME "." picname "." picext "#" NAME "#2"
						else
					        print title "#" newpage "#" pic "#" PICNAME "." picname "." picext "#" NAME "#2"

#					    print title "#" newpage "#" pic "#" PICNAME "." piccount ".jpg#" NAME "#2"
#						print title " (" extra ")#" SRC " " SRC " play \x27" newpage "\x27#" pic "#" PICNAME "." piccount ".jpg#" NAME "#111"
#						print title "#" SRC " " SRC " hoster \x27" newpage "\x27#" pic "#" PICNAME "." piccount ".jpg#" NAME "#111"

			        }
			        
			        newpage = ""
			        title = ""
			        picname = ""
			        pic = ""
                    found = 0
			        next
			    }
                if (found == 1)
                {
#	                newpage = substr($0, 1, length($0) - 1)
##	                newpage = substr($0, 1, length($0))

					if ($0 ~ /\r/ || $0 ~ /\n/)
	                    newpage = substr($0, 1, length($0) - 1)
					else
	                    newpage = substr($0, 1, length($0))

#print "title999", title
				    if (++dup[title] == 1 && title != "" && title !~ "= = =")
				    {
#print "title999a", title
					    piccount += 1

						if(ADD2CHANNEL != 0)
						{
	#					    i = index($0, "/live/") + 6
	#		                j = index(substr($0, i), ".ts") - 1
	#		                id = substr($0, i, j)

							#http://127.0.0.1:4323/vavoo?channel=3160812963e2fed09faa6c
		                    #EXTINF:-1,DE: ARTE
#		                    split(substr($0, 1, length($0)), a, "/")
#		                    id = a[length(a)]
#							gsub(/vavoo\?channel=/, "", id)
#use fullurl for id is better
							id = newpage
							idcmd = "hex_val=$(echo -n \x27" id "\x27 | md5sum | cut -c1-16 | tr \x27\x5B:lower:\x5D\x27 \x27\x5B:upper:\x5D\x27) && echo \x22ibase=16; $hex_val\x22 | " BCBIN

							#print "idcmd: " idcmd
							idcmdck=idcmd | getline idcmdmap
							close(idcmd)
							gsub(/\x23/, ",", idcmdmap)
							if(idcmdck == 1) id = idcmdmap

#                        if(ADD2CHANNEL != 0)
#                        {
                            epgurl = "http://epgurl.dummy.to/" id

                            if(ADD2CHANNEL == 2)
                            {
                                #real    1m3.487s
                                newpage3 = newpage
                                gsub("(&)", "\\\\\\&", newpage3)

								if(LIVE == "1")
                                    cmd2 = cmd2 " -e \"s;#http.*/" id ".ts.*VAVOO.*#;#" newpage3 "\\&livemode=1#;g\" \x5c\n"
								else
	                                cmd2 = cmd2 " -e \"s;#http.*/" id ".*#;#" newpage3 "#;g\" \x5c\n"
                            }
                            else
                            {
                                #real    0m6.421s
                                #user    0m4.576s
                                #sys     0m1.168s
                            }

							if (EPGTYPE == 1)
							{
								epg = "cat /tmp/epg/epgmap.neu.sort | grep \x27\x23" id "$\x27"
######								print "epg: " epg
								epgck=epg | getline epgmap
								close(epg)
								gsub(/\x23/, ",", epgmap)
								if(epgck == 1) epgurl = epgmap
							}
							else if(EPGTYPE == 2)
							{
								epgmap = ""
#								channel = "echo \x22" title "\x22 | sed -e \x27s/ \[.*\]//;s/ (.*)//\x27"
#									channel = "echo \x22" title "\x22 | sed -e \x27s/ [.*]//;s/ (.*)//g\x27 -e \x27s/ UHD$//\x27 -e \x27s/ FHD$//\x27 -e \x27s/ HD$//\x27 -e \x27s/ HD+$//\x27 -e \x27s/ BOX$//\x27 -e \x27s/ BOX1$//\x27 -e \x27s/ 1+$//\x27 -e \x27s/ HEVC$//\x27 -e \x27s/ \x28.b\x29$//\x27 -e \x27s/ \x28.c\x29$//\x27 -e \x27s/ \x28.s\x29$//\x27"
#								channel = "echo \x22" title "\x22 | sed -e \x27s/ [.*]//;s/ (.*)//g\x27 -e \x27s/ UHD$//\x27 -e \x27s/ FHD$//\x27 -e \x27s/ HD$//\x27 -e \x27s/ HD+$//\x27 -e \x27s/ BOX$//\x27 -e \x27s/ BOX1$//\x27 -e \x27s/ 1+$//\x27 -e \x27s/ HEVC$//\x27 -e \x27s/ (.b)$//\x27 -e \x27s/ (.c)$//\x27 -e \x27s/ (.s)$//\x27"
								channel = "echo \x22" title "\x22 | sed -e \x27s/ UHD$//\x27 -e \x27s/ FHD$//\x27 -e \x27s/ HD$//\x27 -e \x27s/ HD+$//\x27 -e \x27s/ BOX$//\x27 -e \x27s/ BOX1$//\x27 -e \x27s/ 1+$//\x27 -e \x27s/ HEVC$//\x27 -e \x27s/ RAW$//\x27 -e \x27s/ .b$//\x27 -e \x27s/ .c$//\x27 -e \x27s/ .s$//\x27 -e \x27s/ \\\x5B.*\\\x5D.*//\x27 -e \x27s/ [.*]//;s/ (.*)//g\x27"
								channelck=channel | getline name
#								print "-----------------------"
#								print "title: " title
#								print "name: " name
#								print "channel: " channel
								close(channel)
								if(channelck == 1)
								{
									epg = "cat " TMP "/vavoo.sql | grep \x27\x22" name "\x22\x27 | cut -d \x27\x22\x27 -f2"
									epgck=epg | getline epgmap
#									print "epgmap: " epgmap
									close(epg)
									gsub(/\x23/, ",", epgmap)
									if(epgck == 1) epgurl = epgmap
								}
							}
							if(LIVE == 1)
	                            cmd = cmd "echo \"" title "#" id "#0#0#0#0#0#0#0#0#0#0#" newpage "&livemode=1#" epgurl "\" >> /tmp/settings/channel.tmp\n"
							else
	                            cmd = cmd "echo \"" title "#" id "#0#0#0#0#0#0#0#0#0#0#" newpage "#" epgurl "\" >> /tmp/settings/channel.tmp\n"
                            cmd = cmd "echo \"" id "#0#0#0#20001#0#0#0#0#0#0#2\" >> /tmp/settings/transponder.tmp\n"
                            cmd = cmd "echo \"LoadM3U (IpTV)#0#20001#3\" >> /tmp/settings/satellites.tmp\n"
                            cmd = cmd "echo \"0#" id "\" >> \"/tmp/settings/bouquets.tithek.autoupdate." NAME "." NEXT ".tv.tmp\"\n"
                            if(++dup[cmd4] == 1)
                                cmd4 = cmd4 "echo \"" NAME "-" NEXT "#0#/mnt/settings/bouquets.tithek.autoupdate." NAME "." NEXT ".tv\" >> /tmp/settings/bouquets.cfg.tmp\n"
                        }
                        else
                        {
#print "title999b1", title
#print "title999b2", newpage
#print "title999b3", title
#print "title999b4", newpage
#print "title999b5" title "#" newpage
#print title "#" newpage "#" 
#pic "#" PICNAME "." picname "." picext "#" NAME "#2"
 
							if(LIVE == 1)
	    					    print title "#" newpage "&livemode=1#" pic "#" PICNAME "." picname "." picext "#" NAME "#2"
							else
	    					    print title "#" newpage "#" pic "#" PICNAME "." picname "." picext "#" NAME "#2"
#    					    print title "#" newpage "#" pic "#" PICNAME "." picname "." picext "#" NAME "#2"
#   					    print title "#" newpage "#" pic "#" PICNAME "." piccount "." picext "#" NAME "#2"
#	    					print title " (" extra ")#" SRC " " SRC " play \x27" newpage "\x27#" pic "#" PICNAME "." piccount ".jpg#" NAME "#111"
#	    					print title "#" SRC " " SRC " hoster \x27" newpage "\x27#" pic "#" PICNAME "." piccount ".jpg#" NAME "#111"
                        }
				    }
				    
				    newpage = ""
				    title = ""
				    picname = ""
				    pic = ""
                    found = 0
				    next
				}

		    }
			END \
				{
                    if(ADD2CHANNEL != 0)
                    {
                        cmd5 = cmd5 "cat /tmp/settings/channel.tmp | sort -u > /tmp/settings/channel\n"
#                        cmd5 = cmd5 "cat /tmp/settings/transponder.tmp | sort -u > /tmp/settings/transponder\n"
                        cmd5 = cmd5 "cp -a \"/tmp/settings/bouquets.tithek.autoupdate." NAME "." NEXT ".tv.tmp\" \"/tmp/settings/bouquets.tithek.autoupdate." NAME "." NEXT ".tv\"\n"
                        cmd5 = cmd5 "cat /tmp/settings/bouquets.cfg.tmp | awk \x27!seen[$0]++\x27 > /tmp/settings/bouquets.cfg\n"
                        cmd5 = cmd5 "cat /tmp/settings/transponder.tmp | awk \x27!seen[$0]++\x27 > /tmp/settings/transponder\n"
                        cmd5 = cmd5 "cat /tmp/settings/satellites.tmp | awk \x27!seen[$0]++\x27 > /tmp/settings/satellites\n"

                        cmd5 = cmd5 "sed s/\"^ *\"// -i /mnt/settings/channel\n"

                        print cmd
 
                        if(ADD2CHANNEL == 2)
                        {
                            cmd2 = cmd2 " -i /tmp/settings/channel.tmp\n"
                            print cmd2
                        }
                        else if(ADD2CHANNEL == 3)
                            print cmd3

                        print cmd4
                        print cmd5
                    }
				}
	    ' >"$TMP/$FILENAME.list"

	fi
	# 30. gebe titan den list namen mit pfad zurueck
#	echo "$TMP/$FILENAME.list"

    if [ "$ADD2CHANNEL" != "0" ];then
        if [ -e $TMP/$FILENAME.list ];then 
            cat $TMP/$FILENAME.list >> $TMP/$FILENAME.cmd.list
#            cp $TMP/$FILENAME.list $TMP/$FILENAME.cmd.list
#            chmod 755 $TMP/$FILENAME.list
#            $TMP/$FILENAME.list
            chmod 755 $TMP/$FILENAME.cmd.list
            $TMP/$FILENAME.cmd.list
        fi
        error=0
        if [ ! -e /tmp/settings/bouquets.cfg ];then error=1; fi
        if [ ! -e /tmp/settings/transponder ];then error=1; fi
        if [ ! -e /tmp/settings/channel ];then error=1; fi
        if [ ! -e /tmp/settings/bouquets.tithek.autoupdate."$NAME"."$NEXT".tv ];then error=1; fi
        if [ "$ADD2CHANNEL" == "1" ];then
            MSG="Create Service Bouquets"
        elif [ "$ADD2CHANNEL" == "2" ];then
            MSG="Update all Services with LoadM3U Streamurl and Service Bouquets"
        fi
        if [ "$error" == "1" ];then
            echo "errormsg: $MSG "$NAME"-"$NEXT" has been creating error in /tmp/settings"
        else
            echo "$MSG "$NAME"-"$NEXT" has been completed in /tmp/settings"
        fi
    else
        cat $TMP/$FILENAME.list | sort -u > $TMP/$FILENAME.sort.list
	    echo "$TMP/$FILENAME.sort.list"
    fi

}

play()
{
	rm $TMP/cache.$PARSER.$INPUT.* > /dev/null 2>&1
	/tmp/localhoster/hoster.sh youtube_dl $URL$PAGE > $TMP/cache.$PARSER.$INPUT.1
	STREAMURL=`cat $TMP/cache.$PARSER.$INPUT.1`
	cat $STREAMURL
#	echo $URL$PAGE
}

hoster()
{
	echo $URL$PAGE
}

######
create_service_bouquets()
{
    search 1
}

#backslash hex
#awk -F, '{print "\x5c" }'
#a single quote hex
#awk -F, '{print "\047" }'
#a single quote octa
#awk -F, '{print "\x27" }'

update_service_bouquets()
{
    NEXT=$(echo $NEXT | tr '+' ' ')

    remove "$NEXT"
    search 1
    save $NEXT
}

update_all_channels()
{
    NEXT=$(echo $NEXT | tr '+' ' ')

    remove "$NEXT"
    search 2
    save "$NEXT"
}

writecmd()
{
#rm -rf /mnt/settings
#cp -a /etc/titan.restore/mnt/settings /mnt

    NEXT=$(echo $NEXT | tr '+' ' ')

    remove "$NEXT"
#only create 0m8.507s
#    search 2
#create and update sat channels with streamid (fast) sed -e .. -i 1m2.206s
    search 2
#create and update sat channels with streamid (slow) sed -- -i 1m28.566s
#    search 4
#create and update sat channels with streamid (very slow) echo sed -i 3m24.186s
#    search 5

    save "$NEXT"
    killall -9 titan
}

save()
{
    if [ ! -z "$1" ];then 
        NEXT="$1"
    fi

    cp /tmp/settings/bouquets.cfg /mnt/settings/bouquets.cfg
    cp /tmp/settings/bouquets.tithek.autoupdate."$NAME"."$NEXT".tv /mnt/settings/bouquets.tithek.autoupdate."$NAME"."$NEXT".tv 
    cp /tmp/settings/channel /mnt/settings/channel
    cp /tmp/settings/transponder /mnt/settings/transponder
    cp /tmp/settings/satellites /mnt/settings/satellites

#    cat /tmp/settings/channel.tmp | sort -u > /mnt/settings/channel
#    cp -a /tmp/settings/bouquets.tithek.autoupdate."$NAME"."$NEXT".tv.tmp /mnt/settings/bouquets.tithek.autoupdate."$NAME"."$NEXT".tv
#    cat /tmp/settings/bouquets.cfg.tmp | awk '!seen[$0]++' > /mnt/settings/bouquets.cfg
#    cat /tmp/settings/transponder.tmp | awk '!seen[$0]++' > /mnt/settings/transponder
#    sed s/"^ *"// -i /mnt/settings/channel
#    remove $NEXT
}

remove()
{
    if [ ! -z "$1" ];then 
        NEXT="$1"
    fi

    if [ -e /tmp/settings ];then
        rm -rf /tmp/settings
    else
        rm /mnt/settings/bouquets.cfg.* > /dev/null 2>&1
        rm /mnt/settings/transponder.* > /dev/null 2>&1
        rm /mnt/settings/channel.* > /dev/null 2>&1
        rm /mnt/settings/satellites.* > /dev/null 2>&1
        rm /mnt/settings/bouquets.tithek.autoupdate."$NAME"."$NEXT".tv.* > /dev/null 2>&1
    fi
}

######

case $INPUT in
	init) $INPUT;;
	mainmenu) $INPUT;;
	play) $INPUT;;
	search) $INPUT;;
	category) $INPUT;;
	hoster) $INPUT;;
	create_service_bouquets) $INPUT;;
    update_service_bouquets) $INPUT;;
    update_all_channels) $INPUT;;
	writecmd) $INPUT;;
	remove) $INPUT;;
	save) $INPUT;;
esac
