#!/bin/sh

# This program creates a image files tree for each image size from a BINS album.
# Edit the variables in the configuration section and run it.

# (c) 2003 Jérôme SAUTRET <jerome@sautret.org>
# This script is distributed under GNU GPL. Ask Stallman for details.

# $Id: anti_bins,v 1.1 2004/05/08 20:02:39 jerome Exp $

set -o nounset

####################################################################
# Configuration section

ALBUM="Album"

# Path of the HTML album directory 
HTML_ALBUM="$HOME/Photos/$ALBUM/html"
# Path of the destination images directory 
IMAGE_ALBUM="$HOME/Photos/$ALBUM/Images"

# size names in the image file, 
# followed by the names of the directories that will be created for each picture sizes
# separated by a colon
IMAGE_SIZES="Sm:Small Images,Med:Medium Images,Lg:Large Images"
#IMAGE_SIZES="Pt:Petites images,Moy:Images moyennes,Gd:Grandes images"

# Copy command
COPY="ln -f"    # use this to create hard links, works only if source & dest are on same partition
#COPY="ln -sf"  # use this to create symbolic links
#COPY="cp -f"   # use this to copy images

# Image extensions
IMAGE_TYPES="jpg|png"

# Set this to 1 when configuration is done.
CONFIGURATION_IS_OK=0

# End of configuration section
#####################################################################

ls --ignore-backups --file-type >/dev/null 2>/dev/null
if [ $? != 0 ] ; then
    echo "This program runs only with a 'ls' supporting the '--file-type' option"
    echo "Install GNU ls or send me a patch..."
    exit 2
fi

if [[ $CONFIGURATION_IS_OK == 0 ]] ; then
    echo "Edit this script to set configuration variables."
    exit 1
fi

IMAGE_SIZES="$IMAGE_SIZES,"
SIZES="`echo "$IMAGE_SIZES" | sed "s/\([^:]*\):[^,]*,/\1 /g"`"

size_name()
{
	echo "$IMAGE_SIZES" | sed "s/^.*$1:\([^,]*\),.*$/\1/"
}

copy_dir()
{
	local SOURCE DEST F
	SOURCE="$1"
	DEST="$2"

	echo "Traitement du répertoire $1"

	cd "$SOURCE"
	for SIZE in $SIZES
	do
		SIZE_NAME="`size_name $SIZE`"
		mkdir -p "$IMAGE_ALBUM/$SIZE_NAME/$DEST" >/dev/null
		for F in `ls --ignore-backups|grep -E "_$SIZE.($IMAGE_TYPES)$"`
		do
			DEST_FILE="`echo "$F" | sed "s/_$SIZE\\././"`"
			DEST_FILE="$IMAGE_ALBUM/$SIZE_NAME/$DEST$DEST_FILE"
			if [ ! -f "$DEST_FILE" ] ; then
				echo "copie de" "$SOURCE$F" vers "$DEST_FILE"
				$COPY "$SOURCE$F" "$DEST_FILE"
			fi
		done
	done
	for F in `ls --ignore-backups --file-type | grep "/$"`
	do
		# Decode URL
		DEST_DIR="`echo "$F"|sed 's/%\([A-F0-9][A-F0-9]\)/\\\\x\\1/g'`"
		DEST_DIR="`printf "$DEST_DIR"`"
		# _ to spaces
		DEST_DIR=`echo "$DEST_DIR"|sed 's/_/ /g'`
		copy_dir "$SOURCE$F" "$DEST$DEST_DIR"
	done
	# Remove dir if empty
	rmdir "$IMAGE_ALBUM/"*"/$DEST" 2>/dev/null
}

copy_dir "$HTML_ALBUM/" ./
