#!/bin/bash

grabber_primary_options () {
	theme_name=dvd
	Link_or_Application=Application
	SOURCE_type=files
	SOURCE_filter=avi,ogm,mpg,divx,mpeg,mov,mp4,mkv,wmv,asf,flv,cue,iso,bin
}

grabber_secondary_options () {
	avatar_title=$(echo ${SOURCE_item##*/} | sed -e 's/[cC][dD][1-9]//' -e 's/[1-9][oO][fF][1-9]//' -e 's/()//' -e 's/[_.]/ /g' -e 's\....$\\')
	avatar_filename=$(echo ${SOURCE_item%/*} | sed -e 's/\//\_/g')_$avatar_title
	avatar_name=$avatar_title
	URL=file://$SOURCE_item
	icon_NAME=$avatar_filename
	Launcher="avatar-factory -al $grabber_name --URL \"$SOURCE_item\" --avatar \"$folder2save/$avatar_filename.desktop\" --name \"$avatar_title\" --title \"$avatar_title\" --icon \"$icons_PATH/$icon_NAME.png\" --DND"
}

get_grabber_picture () {
	local imdb_url photo_url query

    #search cover:
	query=$(echo $avatar_title | sed -e 's/[() -]/+/g')
	imdb_url=$(wget -U firefox -qO - "http://www.google.com/search?hl=en&q=site%3Aimdb.com%2Ftitle+$query" | sed 's/>/\n/g' | grep '<a href="http://www.imdb.com/title' | head -n 1 | cut -d\" -f2)

	if [[ -z $web ]]; then
		imdb_url=$(wget -U firefox -qO - "http://search.yahoo.com/search?p=site%3Aimdb.com%2Ftitle+$query" | sed 's/[\*"]/\n/g' | grep 'imdb.com/title/tt' | grep -v 'http://cache' | head -n 1)
	fi

	grabber_picture=$(wget -U firefox -qO - "$imdb_url" | grep -A1 -i '<div class="photo">' | sed -e 1d -e 's|.*src="||' -e 's/".*//')

	if [[ -z $grabber_picture ]]; then
		photo_url=$(wget -U firefox -qO - "$imdb_url" | grep -m 1 '<div class="media_strip_thumb">' | sed -e 's|.*href="||' -e 's/".*//')
		grabber_picture=$(wget -U firefox -qO - "http://www.imdb.com$photo_url" | grep -A1 '<table id="principal">' | sed -e 1d -e 's|.*src="||' -e 's/".*//')
	fi

    #download cover / blank cover:
	if [[ $grabber_picture ]]; then
		if [[ -n $grabber_picture ]]; then
			wget -q $grabber_picture -O /tmp/thumb$$.${grabber_picture##*.}
			grabber_picture=/tmp/thumb$$.${grabber_picture##*.}

			if [[ -f $icons_PATH/$icon_NAME-NO-COVER.png ]]; then
				force_avatar_build=yes
			fi
		else
			if [[ -f $icons_PATH/$icon_NAME-NO-COVER.png ]]; then
				grabber_picture=
				temporary_icon=yes
			else
				grabber_picture=$avatar_factory_PATH/imdb-nocover.gif
			fi

			icon_NAME=$icon_NAME-NO-COVER
		fi
	fi
}
