#!/bin/bash

url="http://s.tv.kwaoo.net/playlist.m3u"


path=$(dirname "$0")

pathinput=$path"/playlist.m3u"

pathcsv=$path"/knet.csv"
pathm3u=$path"/knet.m3u"
pathm3utnt=$path"/knet_tnt.m3u"
pathm3uradio=$path"/knet_radio.m3u"

pathkodi="/home/kodi/"

i=0

if [ ! -f $pathinput ];then
	wget -P $path $url
fi

sed ':a;N;$!ba;s/#EXTM3U\n//g;s/#EXTINF:0,//g;s/\nhttp:/|http:/g;s/\nhttps:/|https:/g;s/\.\ /|/g;s/\ /_/g' $pathinput > $pathcsv

eCollection=( $(cat $pathcsv ) )
#echo "${eCollection[2]}" | cut -d "|" -f1

echo "#EXTM3U" > $pathm3u
echo "#EXTREM:Début des programmes :" >> $pathm3u

echo "#EXTM3U" > $pathm3utnt
echo "#EXTREM:Début des programmes :" >> $pathm3utnt
		
echo "#EXTM3U" > $pathm3uradio
echo "#EXTREM:Début des programmes :" >> $pathm3uradio
		
for c in "${eCollection[@]}"; do

	t1='#EXTINF:0 tvg-id="'
	t2=$(echo "${c}" | cut -d "|" -f2)
	t3='" tvg-logo="'
	t4=$(echo "${c}" | cut -d "|" -f2 | tr 'A-Z' 'a-z')
	t5='.png" group-name="TNT" ,'
	t6=$(echo "${c}" | cut -d "|" -f1)
	t7='. '
	t8=$(echo "${c}" | cut -d "|" -f2)
	t9=$(echo "${c}" | cut -d "|" -f3)
	
	if [ $t6 == "1" ]; then
		((i++))
		echo $i
	fi
	
	if [ $i == "1" ]; then
		t5='.png" group-name="TNT" ,'
		echo "$t1$t2$t3$t4$t5$t6$t7$t8" >> $pathm3utnt
		echo "$t9" >> $pathm3utnt
	elif [ $i == "2" ]; then
		t5='.png" group-name="Radio" ,'
		echo "$t1$t2$t3$t4$t5$t6$t7$t8" >> $pathm3uradio
		echo "$t9" >> $pathm3uradio
	elif [ $i > "2" ]; then
		t5='.png" group-name="Other" ,'
	fi

	echo "$t1$t2$t3$t4$t5$t6$t7$t8" >> $pathm3u
	echo "$t9" >> $pathm3u

done

if [ -d $pathkodi ];then
	cp $pathm3u $pathkodi
	cp $pathm3utnt $pathkodi
	cp $pathm3uradio $pathkodi
fi

exit 0