#!/bin/sh
# Create a html gallery
FILE="";
let "nbfiles = $#"
kdeinstdir=`kde4-config --prefix`
KIM_DIR=$kdeinstdir/share/kim/gallery
TITLE=`kdialog --inputbox "Kim - Title:" "My title ..."`;
AUTHOR=`kdialog --inputbox "Kim - Author:" "$USER"`;
DATE=`date '+%A %-d %B %Y'`;
SCALE_1="800x800";
SCALE_2="200x200";
K=`kdialog --inputbox "Kim - Number of columns:" "4"`;
DIR=`kdialog --getexistingdirectory /home/$USER`;
W="200";
H="150";

dbusRef=`kdialog --progressbar "Kim - Initialising ..." $nbfiles`
qdbus $dbusRef showCancelButton true

# Creation of directories
mkdir $DIR/images;
mkdir $DIR/thumbs;
# Header of $DIR/index.html
cp $KIM_DIR/index.part1 $DIR/index.html;
echo '<h1>'$TITLE'</h1>' >> $DIR/index.html;
echo '<h5>Author: '$AUTHOR'<br>Date: '$DATE'</h5>' >> $DIR/index.html;
echo '<table><tr>' >> $DIR/index.html;

compteur=0;
tmp=0;
for i in "$@";do
	if [ -f "$i" ];then
		#test if cancel button has been pushed
		if [[ "$(qdbus $dbusRef wasCancelled)" == "true" ]] ; then
			qdbus $dbusRef close
			exit 1
		fi
		let "compteur +=1"
		let "tmp +=1"
		FILE="$i";
		IMAGE=`basename "$FILE"`;
		convert -resize $SCALE_1 "$FILE" $DIR/images/"$IMAGE";
		convert -resize $SCALE_2 "$FILE" $DIR/thumbs/"$IMAGE";
		W2=`identify -format "%w" $DIR/images/"$IMAGE"`;
		H2=`identify -format "%h" $DIR/images/"$IMAGE"`;
		echo '<td align='center'>' >> $DIR/index.html;
		if [ "$H2" -lt "$W2" ];
		then echo '<a href="images/'"$IMAGE"'"><img class="photo" src="thumbs/'"$IMAGE"'" width="'$W'" height="'$H'" alt="thumbs/'"$IMAGE"'" title="'"$IMAGE"'"></a>' >> $DIR/index.html;
		else echo '<a href="images/'"$IMAGE"'"><img class="photo" src="thumbs/'"$IMAGE"'" width="'$H'" height="'$W'" alt="thumbs/'"$IMAGE"'" title="'"$IMAGE"'"></a>' >> $DIR/index.html;
		fi;
		echo '<p>'"$IMAGE"'</p>' >> $DIR/index.html;
		echo '</td>' >> $DIR/index.html;
		if [ "$tmp" -eq "$K" ];
		then 	echo '</tr><tr>' >> $DIR/index.html;
			tmp=0;
		fi
		qdbus $dbusRef setLabelText "Kim - Treatment of file: "$IMAGE""
 		qdbus $dbusRef org.freedesktop.DBus.Properties.Set org.kde.kdialog.ProgressDialog value "$compteur"
	fi;
done

cat $KIM_DIR/index.part2 >> $DIR/index.html;
qdbus $dbusRef close;

konqueror $DIR/index.html;