#!/bin/bash

INFO="mkgallery.sh    mail AT patrick-nagel DOT net    2008-04-03"
# Depends on: ImageMagick (convert), exiv2 and standard shell tools (sed, cut, grep, mktemp)
# Optional:   Lightbox JS v2.0 (http://http://www.huddletogether.com/projects/lightbox2/) for
#             fancy JavaScript effects.

#     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 2 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, write to the Free Software
#     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


# Configuration

TEMPLATE_FILE="./mkgallery-template.txt"

# Those values will be overwritten by the template file
GALLERY_TITLE="${USER}'s gallery"
THUMBNAIL_SIZE="120x120"
COLUMNS="4"
HTML="index.html"
CSS="gallery.css"
EXIF="yes"
FANCY="no"

# Configuration end


# Heading

echo "${INFO}"
echo


# Functions

function writeTemplateSettings() {
	# Make a backup
	mv ${TEMPLATE_FILE} ${TEMPLATE_FILE}.backup &>/dev/null

	echo "Template file for mkgallery.sh" >${TEMPLATE_FILE}
	echo "* Make sure that there is exactly one TAB between the element and your text!" >>${TEMPLATE_FILE}
	echo >>${TEMPLATE_FILE}
	echo -e "You can keep the default values or change them to your needs:\n" >>${TEMPLATE_FILE}
	echo -e "GALLERY TITLE\t${GALLERY_TITLE}" >>${TEMPLATE_FILE}
	echo -e "THUMBNAIL SIZE\t${THUMBNAIL_SIZE}" >>${TEMPLATE_FILE}
	echo -e "THUMBN. COLUMNS\t${COLUMNS}" >>${TEMPLATE_FILE}
	echo -e "HTML FILENAME\t${HTML}" >>${TEMPLATE_FILE}
	echo -e "CSS FILENAME\t${CSS}" >>${TEMPLATE_FILE}
	echo -e "SHOW EXIF INFO\t${EXIF}" >>${TEMPLATE_FILE}
	echo -e "FANCY JSCRIPT\t${FANCY}" >>${TEMPLATE_FILE}
	echo >>${TEMPLATE_FILE}

	echo >>${TEMPLATE_FILE}
	echo "Here is a list of your images. Add a description at the end of the line, if" >>${TEMPLATE_FILE}
	echo -e "you want some text to appear below each thumbnail.\n" >>${TEMPLATE_FILE}
}

function readTemplateSettings() {
	# Read settings from template file and overwrite default values
	GALLERY_TITLE=$(grep "^GALLERY TITLE" "${TEMPLATE_FILE}" | cut -f2)
	THUMBNAIL_SIZE=$(grep "^THUMBNAIL SIZE" "${TEMPLATE_FILE}" | cut -f2)
	COLUMNS=$(grep "^THUMBN. COLUMNS" "${TEMPLATE_FILE}" | cut -f2)
	HTML=$(grep "^HTML FILENAME" "${TEMPLATE_FILE}" | cut -f2)
	CSS=$(grep "^CSS FILENAME" "${TEMPLATE_FILE}" | cut -f2)
	EXIF=$(grep "^SHOW EXIF INFO" "${TEMPLATE_FILE}" | cut -f2)
	FANCY=$(grep "^FANCY JSCRIPT" "${TEMPLATE_FILE}" | cut -f2)
}

function newTemplate() {
	echo "Creating new template file \"${TEMPLATE_FILE}\"..."
	echo

	rm -f tn_*.jpg 2>/dev/null

	writeTemplateSettings

	ls -1 *.jpg | sed -e 's/$/\t/' >>${TEMPLATE_FILE}

	echo "Done."
	echo
}

function updateTemplate() {
	if [ ! -f ${TEMPLATE_FILE} ]; then {
		echo "Error: \"${TEMPLATE_FILE}\" not found. Cannot update."
		echo
		return 1
	}
	fi

	echo "Updating template file \"${TEMPLATE_FILE}\"..."
	echo

	TEMP=$(mktemp)
	rm -f tn_*.jpg 2>/dev/null

	for i in *.jpg; do {
		# Take existing entry to temporary file, or generate a new one
		grep "^${i}" "${TEMPLATE_FILE}" >>${TEMP} || echo -e "${i}\t" >>${TEMP}
	}
	done

	readTemplateSettings

	writeTemplateSettings

	sort ${TEMP} >>${TEMPLATE_FILE}

	rm -f ${TEMP}

	echo "Done."
	echo
}

function htmlTop() {
	echo -en "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\">
<head>
  <meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\" />
  <title>${GALLERY_TITLE}</title>
"
	echo -en "
  <link rel=\"stylesheet\" href=\"${CSS}\" type=\"text/css\" media=\"screen\" />
"

	if [[ ${FANCY} == "yes" ]]; then {
		echo -en "
  <script type=\"text/javascript\" src=\"js/prototype.js\"></script>
  <script type=\"text/javascript\" src=\"js/scriptaculous.js?load=effects,builder\"></script>
  <script type=\"text/javascript\" src=\"js/lightbox.js\"></script>
  <link rel=\"stylesheet\" href=\"css/lightbox.css\" type=\"text/css\" media=\"screen\" />"
	}
	fi

	echo -en "
</head>
<body style=\"direction: ltr;\">

<h1>${GALLERY_TITLE}</h1>

"
}

function htmlTable() {
	CELLCOUNT=0
	echo "<table cellspacing=\"10\" cellpadding=\"10\">"

	for i in *.jpg; do {
		CELLCOUNT=$(( ${CELLCOUNT} + 1 ))
		
		if (( ${CELLCOUNT} == 1 )); then {
			echo "  <tr>"
		}
		fi

		IMAGE_FILENAME="${i}"
		THUMB_FILENAME="$(echo "${i}" | sed -e 's/^/tn_/' -e 's/jpg$/gif/')"

		if [ -f ${TEMPLATE_FILE} ]; then {
			# Fetch description from template
			DESCRIPTION="$(grep "${IMAGE_FILENAME}" "${TEMPLATE_FILE}" | cut -f2)"
		}
		fi

		# Fetch EXIF data from image file
		if [[ "${EXIF}" == "yes" ]]; then {
			EXIF_FOCAL_LENGTH="$(exiv2 ${IMAGE_FILENAME} 2>/dev/null | grep "^Focal length" | cut -b19-)"
			EXIF_APERTURE="$(exiv2 ${IMAGE_FILENAME} 2>/dev/null | grep "^Aperture" | cut -b19-)"
			EXIF_EXPOSURE_TIME="$(exiv2 ${IMAGE_FILENAME} 2>/dev/null | grep "^Exposure time" | cut -b19-)"
			EXIF_ISO_SPEED="$(exiv2 ${IMAGE_FILENAME} 2>/dev/null | grep "^ISO speed" | cut -b19-)"
			EXIF_STRING="${EXIF_FOCAL_LENGTH}, ${EXIF_APERTURE}, ${EXIF_EXPOSURE_TIME}, ISO ${EXIF_ISO_SPEED}"
		}
		fi

		# How EXIF_STRING will look like, if there is no EXIF information in the image
		EMPTY_EXIF_STRING=", , , ISO "

		if [[ "${FANCY}" == "yes" ]]; then
		{
			echo -en "    <td valign=\"bottom\" align=\"center\">\n      <a href=\"${IMAGE_FILENAME}\" rel=\"lightbox[gallery]\" title=\""

			if [[ "${DESCRIPTION}" != "" ]]; then {
				echo -en "${DESCRIPTION}"
	
				if [[ "${EXIF}" == "yes" ]] && [[ "${EXIF_STRING}" != "${EMPTY_EXIF_STRING}" ]]; then {
					echo -en " / "
				}
				fi
			}
			fi
	
			if [[ "${EXIF}" == "yes" ]] && [[ "${EXIF_STRING}" != "${EMPTY_EXIF_STRING}" ]]; then {
				echo -en "${EXIF_STRING}"
			}
			fi
	
			echo -e "\"><img src=\"${THUMB_FILENAME}\" alt=\"${DESCRIPTION}\" /></a>"
		}
		else
		{
			echo -en "    <td valign=\"bottom\" align=\"center\">\n      <a href=\"${IMAGE_FILENAME}\"><img src=\"${THUMB_FILENAME}\" alt=\"${DESCRIPTION}\" /></a>"

		}
		fi

		echo -en "\n      <p>\n        "
	
		if [[ "${DESCRIPTION}" != "" ]]; then {
			echo -en "${DESCRIPTION}"

			if [[ "${EXIF}" == "yes" ]] && [[ "${EXIF_STRING}" != "${EMPTY_EXIF_STRING}" ]]; then {
				echo -en "<br />"
			}
			fi
		}
		fi

		if [[ "${EXIF}" == "yes" ]] && [[ "${EXIF_STRING}" != "${EMPTY_EXIF_STRING}" ]]; then {
			echo -en "<small>${EXIF_STRING}</small>"
		}
		fi

		echo -e "\n      </p>\n    </td>"


		if (( ${CELLCOUNT} == ${COLUMNS} )); then {
			echo "  </tr>"
			CELLCOUNT=0
		}
		fi
	}
	done

	if (( ${CELLCOUNT} != 0 )); then {
		echo "  </tr>"
	}
	fi

	echo -e "</table>"
}

function htmlBottom() {
	echo -en "\n<p>\n  <small>Powered by <a href=\"http://patrick-nagel.net/scripts/mkgallery/mkgallery.sh\">mkgallery.sh</a></small>\n</p>\n\n"
	echo -en "</body>\n</html>"
}

function createGallery() {

	if [ ! -f ${TEMPLATE_FILE} ]; then {
		echo "No template file found. Using default settings."
		echo
	}
	else {
		echo "Creating gallery from \"${TEMPLATE_FILE}\"..."
		echo
		readTemplateSettings
	}
	fi

	echo "Title: ${GALLERY_TITLE} | Thumbnail size: ${THUMBNAIL_SIZE} | Columns: ${COLUMNS}"
	echo "Resulting HTML file: ${HTML} | Show EXIF: ${EXIF}"

	if [[ "${FANCY}" == "yes" ]]; then {
		echo
		echo "Fancy JavaScript is active. If you specified a CSS file, please take care that"
		echo "it doesn't interfere with that one from Lightbox (css/lightbox.css)."
		echo
		echo "In order to get the JavaScript part to work, please download the ZIP archive"
		echo "from http://www.huddletogether.com/projects/lightbox2/ and unpack it into"
		echo "this directory."
	}
	else
	{
		echo "CSS file: ${CSS}    (Fancy JavaScript is disabled)"
	}
	fi
	
	echo

	echo -n "Generating thumbnails "
	rm -f tn_*.jpg 2>/dev/null
	for i in *.jpg; do {
		convert -resize "${THUMBNAIL_SIZE}" "${i}" "tn_${i%.???}.gif"
		echo -n "."
	}
	done
	echo " done."

	echo -n "Generating ${HTML} ..."
	htmlTop >${HTML}
	htmlTable >>${HTML}
	htmlBottom >>${HTML}
	echo " done."
	echo
}

# Main

if [[ "$2" != "" ]]; then {
	TEMPLATE_FILE="$2"
}
fi


if [[ "$1" == "-n" ]]; then {
	newTemplate
	exit
}
fi

if [[ "$1" == "-u" ]]; then {
	updateTemplate
	exit
}
fi

if [[ "$1" == "-c" ]]; then {
	createGallery
	exit
}
fi

echo "-n                 Create new template file (${TEMPLATE_FILE}). Edit this file with"
echo "                   a text editor and add/change all relevant parts. Afterwards, call this"
echo "                   script again with the -c parameter. Overwrites an existing template file."
echo "-n <templatefile>  Create new template file <templatefile>."
echo
echo "-u                 Update ${TEMPLATE_FILE} (appends new images to the file list in the template."
echo "-u <templatefile>  Update <templatefile>."
echo
echo "-c                 Create gallery from template file (${TEMPLATE_FILE})."
echo "-c <templatefile>  Create gallery from <templatefile>."
echo
echo "* Make sure that all images have a \".jpg\" extension. Notice all lower case."
echo "* Make sure your image filenames don't start with \"tn_\" or they will be deleted."
echo
