#!/bin/bash


#This software search and download videos from www.youtube.com
#Copyright (C) 2009 Enrico Cherubini <kevin@bestkevin.com>
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

if [ -z $1 ]
then
	echo "Sintassi: GetYouTube.sh cosacercare"
	exit 0
fi

YOUTUBEDLPATH=/usr/bin/
DOWNLOADPATH=/home/kevin/Download/Aikido/DL


wget "http://www.youtube.com/results?search_query=$1&search=Search" -O youtube -o log

#for video in `cat youtube | grep "watch?v=" | grep onclick | cut -d "\"" -f 2 | sort | uniq`
for video in `grep "watch?v" youtube | grep Wrapper | cut -d "\"" -f 12 | grep watch | sort | uniq`
do
	echo "http://www.youtube.com$video"
	# http://www.arrakis.es/~rggi3/youtube-dl/
	Description1=`grep $video youtube  | head -n 1 | cut -d "\"" -f 16 | sed -e s/\ /_/g`
	#Description2=`echo $video | cut -d "=" -f 2`
	Filename=$Description1.flv
	#echo "$YOUTUBEDLPATH/youtube-dl.py http://www.youtube.com$video -o $DOWNLOADPATH/$Filename"
	$YOUTUBEDLPATH/youtube-dl -o $DOWNLOADPATH/$Filename http://www.youtube.com$video
done

next=`grep pagerNotCurrent youtube | tail -n 1 | cut -d "'" -f 2`

#while [ -n $next ]
while [ $next ]
do
	for video in `grep "watch?v" youtube | grep Wrapper | cut -d "\"" -f 12 | grep watch | sort | uniq`
	do
		echo "http://www.youtube.com$video"
		# http://www.arrakis.es/~rggi3/youtube-dl/
		Description1=`grep $video youtube  | head -n 1 | cut -d "\"" -f 16 | sed -e s/\ /_/g`
		#Description2=`echo $video | cut -d "=" -f 2`
		Filename=$Description1.flv
		#echo "$YOUTUBEDLPATH/youtube-dl.py http://www.youtube.com$video -o $DOWNLOADPATH/$Filename"
		$YOUTUBEDLPATH/youtube-dl -o $DOWNLOADPATH/$Filename http://www.youtube.com$video
	done
	next=`grep pagerNotCurrent youtube | tail -n 1 | cut -d "'" -f 2`
done

