#!/bin/bash
# Pequeño script para descargar un canal entero de youtube
cierralanzador

case $LANG in
    es*)		
	texturl="Copia y pega aquí la dirección del vídeo, canal o lista de reproducción." 		
	;;
    gl*)
	texturl="Copia e pega aquí o endrezo do vídeo, canle ou lista de reprodución."    
	;;
    ca*)
	texturl = "Còpia i pega aquí l'adreça del vídeo, canal o llista de reproducció."    
	;;
    *)	# Other
	texturl="Copy & paste here the video URL, channel or playlist."		
	;; 
esac

rutaprograma=`dirname "$0"`

hayinternete=`hayinternet`

if [ "$hayinternete" = "up" ];then
	versioninstalada=`youtube-dl --version`
	versionactualizada=`wget youtube-dl.org -O -|grep Latest|cut -d "(" -f 2|cut -d ")" -f1|cut -d "v" -f2`
	if [ "$versioninstalada" = "$versionactualizada" ];then
		echo "youtube-dl está actualizado"
	else
		mensaje "Un segundo. Actualizando el programa youtube-dl..."&
		sleep 4;killall notify-osd
		update-youtube-dl
		#actualiza /opt/youtube-dl/youtube-dl
	fi

fi

SELECTION="`xclip -o`"
if [ "$SELECTION" = "" ];then
	URL=$(zenity --entry --text "$texturl" --entry-text "http://www.youtube...")
else
	URL=$(zenity --entry --text "$texturl" --entry-text "$SELECTION")	
fi
	if [ "$URL" == "" ];then exit 0;fi

	DESTINO="`zenity --file-selection --directory`"
		if [ "$DESTINO" == "" ];then exit 0;fi
	cd "$DESTINO"
cat <<-EOF >update
#!/bin/bash
youtube-dl -citw ${URL}|zenity --text-info
EOF
chmod +x update

youtube-dl -citw "$URL"|zenity --text-info



#Bucle para comprobar que zenity está funcionando,
#si se ha pulsado cancelar, se canceralá wget.
funcionando=0
while [ $funcionando -eq 0 ]
do
if [ -z "$(pidof zenity)" ]
then
  pkill youtube-dl
  funcionando=1
fi
done
