#!/bin/bash

# scale.filmweb.pl: downloads the images linking to the articles, videos, and news
#                   from Polish-language website http://www.filmweb.pl

#
# CONFIGURATION SECTION BEGINS HERE
#

Configuration=".wmphoto+4"
Browser="firefox"
Backup="no"

#
# CONFIGURATION SECTION ENDS HERE
#

if [ "`which lynx 2> /dev/null`" == "" ]
then
    echo "scale.rottentomatoes.com: there's no lynx program in the system"
    exit
fi

if [ "$Backup" == "yes" ] && [ ! -d backup ]
then
    mkdir backup
fi

for file in `find . -maxdepth 1 -name "*.xpm.gz" -mtime 1`
do
    if [ "$Backup" == "yes" ]
    then
	mv $file backup
	mv `echo $file | sed 's/.xpm.gz//'` backup
	mv `echo $file | sed 's/.xpm.gz/.jpg/'` backup
    else
	rm $file
	rm `echo $file | sed 's/.xpm.gz//'`
	rm `echo $file | sed 's/.xpm.gz/.jpg/'`
    fi
done

lynx --source http://www.filmweb.pl > index.html

for image in `cat index.html | sed -E 's/</\n</g;s/>/>\n/g' | grep '1.fwcdn.pl/an/' | sed 's/.*src="//;s/".*//' | grep '7.jpg'`
do
    wget -Nnd $image 2> /dev/null
    destination=`echo $image | sed 's#.*/##;s#\.jpg$##'`
    if [ ! -f $destination.xpm.gz ] || [ $destination.jpg -nt $destination.xpm.gz ]
    then
	cat index.html | sed 's#<#\n<#g' | grep -B 1 "$image" | head -n 1 > $destination
	sed -i 's#.*a href="##;s#".*##' $destination
	sed -i "s#^#$Browser http://www.filmweb.pl#" $destination
	echo "/home/$USER/$Configuration/command" >> $destination
    fi
done

for source in *.jpg
do
    destination=`echo $source | sed 's#\.jpg$##'`
    if [ ! -f $destination.xpm.gz ] || [ $source -nt $destination.xpm.gz ]
    then
	touch $destination
	montage $source -crop 178x178+29+0 -background gray -colors 256 -geometry 54x54 -size 54x54 -unsharp 0.125 +adjoin "$destination.xpm.gz"
    fi
done
