#!/bin/bash

#########################################################################
# This program is free software: you can redistribute it and/or modify  #
# it under the terms of the version 3 of the GNU General Public License #
# as published by the Free Software Foundation.                         #
#                                                                       #
# 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/>.  #
#                                                                       #
# Written by and Copyright (C) Francois Fleuret                         #
# Contact <francois@fleuret.org> for comments & bug reports             #
#########################################################################

function error () {
    echo $1 1>&2
    exit 1
}

######################################################################
# Create the directories

if [[ -z $1 ]] || [[ -z $2 ]]; then
    echo "$0 <image directory> <result directory>"
    exit 1
fi

if [[ ! -d $1 ]]; then
    echo "Can not find directory $1"
    exit 1
fi

mkdir $2 || error "Can not create $2."
mkdir $2/pics || error "Can not create $2/pics"
mkdir $2/thumbs || error "Can not create $2/thumbs"

######################################################################
# Generate the html header

cat > $2/index.html <<EOF
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title></title>
</head>

<body>

EOF

######################################################################
# Generate the thumbnails, html content and copy the images

for i in $(find $1 -type f | sort); do
    FILENAME=$(basename $i)
    convert 2> /dev/null -geometry 180x120 $i $2/thumbs/${FILENAME}.jpg

    if [[ $? == 0 ]]; then
        echo "Copying ${FILENAME}"
        cp $i $2/pics/${FILENAME}
        echo "<a href=\"./pics/${FILENAME}\"><img src=\"./thumbs/${FILENAME}.jpg\" /></a>" >> $2/index.html
    else
        echo "Ignoring $i (not an image?)"
    fi

done

######################################################################
# Generate the footer of the html file

cat >> $2/index.html <<EOF
</body>

</html>
EOF

######################################################################

