#!/bin/bash 
# Author: Roberto Muñoz Gomez <munoz.roberto@gmail.com>
# Date: 26/09/2011
# Description: Script to download subtitles of Tv Shows from subtitulos.es or any other
# webpage based on wikisubtitles
#
# NOTE: Only tested with subtitulos.es
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
#

DEBUG="" #Initialize this variable to enable debug mode
#DEBUG="YES"

LANGUAGES="5 4 6" #Language iteration list (blank separated). If first do not exists, try next.
#Language list obtained from http://www.subtitulos.es/newsub.php
LANGUAGES_str[1]="English"
LANGUAGES_str[10]="Brazilian"
LANGUAGES_str[11]="German"
LANGUAGES_str[12]="Català"
LANGUAGES_str[13]="Euskera"
LANGUAGES_str[14]="Czech"
LANGUAGES_str[15]="Galego"
LANGUAGES_str[16]="Turkish"
LANGUAGES_str[17]="Nederlandse"
LANGUAGES_str[18]="Swedish"
LANGUAGES_str[19]="Russian"
LANGUAGES_str[4]="Español"
LANGUAGES_str[5]="Español (España)"
LANGUAGES_str[6]="Español (Latinoamérica)"
LANGUAGES_str[7]="Italian"
LANGUAGES_str[8]="French"
LANGUAGES_str[9]="Portuguese"
LANGUAGES_str[20]="Hungarian"
LANGUAGES_str[21]="Polish"
LANGUAGES_str[22]="Slovenian"
LANGUAGES_str[23]="Hebrew"
LANGUAGES_str[24]="Chinese"
LANGUAGES_str[25]="Slovak"

BASE="http://www.subtitulos.es"

chapterpage=$(mktemp)
trap "rm $chapterpage" 0
if [ "$DEBUG" ];then
	log=$(mktemp)
	cat > $log <<-EOF
	THIS IS THE DEBUG OUTPUT
	IF YOU DO NOT WANT TO SEE THIS MESSAGE
	UNINITALIZE THE DEBUG VARIABLE IN $0

	----------------8<----------------8<----------------

	EOF
	trap "zenity --text-info --filename=$log --title 'Debug Output';rm $log $chapterpage" 0
	set -x
	exec &>> $log
fi

TOTAL="$#"
already_done=1
while [ "$1" ];do
	ORIGINAL_FILENAME="$(echo -e "$(echo $1|sed "s/%\([0-9a-fA-F][0-9a-fA-F]\)/\\\x\1/g")")" #Regenerating original filename from escaped chars
	DIR="$(dirname "$ORIGINAL_FILENAME")"
	if [ ! -d "$DIR" ];then
		echo "# Error trying to access to $DIR...skipping"
		sleep 5
		shift
		continue
	fi
	pushd "$DIR" &>/dev/null
	FILE="$(basename "$ORIGINAL_FILENAME")"
	echo "# ($already_done/$TOTAL) Parsing $FILE..."

	#Obtain a guessed show name from filename
	SHOW="$(echo "$FILE"|sed -e "s/^\(.*\)\.[sS][0-9]\+[eE][0-9]\+[\.-].*$/\1/g")" 
	SHOW=${SHOW//./-} #Blanks need to be translated to "-" and blanks are "." in filenames

	#Obtain a guesses chapter
	CHAPTER="$(echo "$FILE"|sed -e "s/.*[sS]\([0-9]\+\)[eE]\([0-9]\+\).*/\1x\2/g" )" #Parsing the chapter code to get something like 03x04

	SHOW_orig="$SHOW"
	for regexp_show in "" 's/-\([^-]*\)$/-(\1)/' 's/-[^-]*$//g';do
		# If first guess with show title is wrong, try put the last word between (). Very useful for shows like V.(2009) because in the filename doesn't appear the ()
		# Also try to download without the last word. For example for Thundercats-2011 y only want Thundercats.
		[ "$regexp_show" ] && SHOW="$(echo $SHOW_orig|sed $regexp_show)"

		echo "# ($already_done/$TOTAL) Downloading subtitle show $SHOW chapter $CHAPTER in directory $DIR ..."
		URLCHAPTER="$BASE/$SHOW/$CHAPTER"
		echo "# ($already_done/$TOTAL) Looking for the code of show $SHOW chapter $CHAPTER ..."
		wget -qO $chapterpage "$URLCHAPTER"
		chaptercode="$(cat $chapterpage |sed  -n "s/.*ajax_getComments.php?id=\([0-9]\+\).*/\1/gp")"
		[ "$chaptercode" ] && break || sleep 1
	done
	if [ -z "$chaptercode" ];then
		echo "# ($already_done/$TOTAL) Code for $SHOW $CHAPTER not found"
		sleep 1
	else
		echo "# ($already_done/$TOTAL) Found"
		for lang in $LANGUAGES;do
			#Check if translation is finished
			URLSUBTITLE="$BASE/updated/$lang/$chaptercode"
			if ! grep -q "$URLSUBTITLE" $chapterpage;then #If the subtitles are not completed...
				completed="$(grep -B10 "jointranslation.php?id=$chaptercode&fversion=[0-9]\+&lang=$lang" $chapterpage|grep -o "[^[:space:]]\+%")"
				if [ "$completed" ];then
					if zenity --question --text="Subtitle for $SHOW $CHAPTER in ${LANGUAGES_str[$lang]} is not complete. Only $completed is done." --ok-label="Download" --cancel-label="Cancel";then
						if wget -q -O "${FILE%.*}.srt" --referer="$URLCHAPTER" "$URLSUBTITLE/0" ;then
							echo "# ($already_done/$TOTAL) $SHOW $CHAPTER SUCCESS"
							break;
						else
							echo "# ($already_done/$TOTAL) $SHOW $CHAPTER FAIL"
							sleep 1
						fi
					fi
				fi
			else #If they are finished...
				url="$(grep -o "$URLSUBTITLE/[0-9]\+" $chapterpage|tail -1)"
				echo "# ($already_done/$TOTAL) Trying download show $SHOW chapter $CHAPTER in ${LANGUAGES_str[$lang]}..."
				if wget -q -O "${FILE%.*}.srt" --referer="$URLCHAPTER" "$url" ;then
					echo "# ($already_done/$TOTAL) $SHOW $CHAPTER SUCCESS"
					break;
				else
					echo "# ($already_done/$TOTAL) $SHOW $CHAPTER FAIL"
					sleep 1
				fi
			fi
		done
	fi
	popd &>/dev/null
	shift
	((already_done++))
done
#|zenity --progress --title "Downloading subtitles" --text "Parsing parameters..." --auto-close --auto-kill --pulsate


