#!/bin/sh

# Make thumbnails. Optionally rename files.
# Quick, dirty, etc.
# Waider June 2000-February 2001

VARS=`getopt vrct "$@"`
eval set -- "$VARS"
while true; do
  case "$1" in
    -v) VIEW=1; shift;;
    -r) RENAME=1; shift;;
    -c) CAPTION=1; shift;;
    -t) THUMBSONLY=1; shift;;
    --) shift; break;;
    *) echo "error!"; exit 1;;
  esac
done

# Pick up the index page
if [ -z "$THUMBSONLY" ]
then
index=$1

  # Make sure it's kosher
  if [ -f "$index" ]
  then
	if file "$index" | grep -i "<html>" >/dev/null 2>&1
	then
		echo "Output to HTML file $1"
		shift
	else
		echo "$index isn't a HTML file, using index.html instead."
		index="index.html"
		if file "$1" | egrep -i "jpeg|gif" >/dev/null 2>&1
		then
			echo "Looks like $1 is an image, actually. Coping."
		else
			shift
		fi
	fi
  else
	shift
  fi
else
  index="dummy"
fi

if [ -z "$index" -o -z "$1" ]
then
	echo "Usage: $0 [-vrct] index images" >&2
    exit 1
fi

if [ -z "$THUMBSONLY" ]
then
  if [ -f "$index" ]
  then
	echo "$index exists, appending."
  else
	echo "Inserting $index prologue."
	# Index prologue
	echo "<html>" > $index
	echo "<head>" >> $index
	echo "<title></title>" >> $index
	echo "<link rel=\"stylesheet\" href=\"../../../waider.css\">" >> $index
	echo "</head>" >> $index
	echo "<body>" >> $index
  fi
fi

for i in $@
do
	echo $i
	caption=

	if [ ! -z "$VIEW" ]
	then
		#xview $i
		$HOME/src/perl/mkthumbs.pl $i
	fi

    if [ ! -z "$RENAME" ]
	then
		echo -n "Rename $i: "
		read rename

		if [ ! -z "$rename" ]
		then
            if echo $rename | grep " " 2>/dev/null >/dev/null
			then
                echo "You probably meant that to be the caption. Coping."
				caption=$rename
            else
				if [ -f $rename ]
				then
					echo "Not renaming, you already have a $rename"
				else
					mv $i $rename
					i=$rename
				fi
			fi
		fi
	fi

	# make thumbnail
	if echo $i | grep "/" >/dev/null 2>&1
	then
		thumb=`echo $i | sed 's/\/\([^\/]*\)$/\/thumb-\1/'`
	else
		thumb="thumb-$i"
	fi
	export thumb

	# FIXME what if it's not a JPEG!
	# FIXME #2 should rescale to a standard size
	# FIXME #3 do we need to rotate the image?
	djpeg -scale 1/8 "$i" | cjpeg > $thumb;

	# Ask for a caption
    if [ ! -z "$CAPTION" ]
    then
      echo -n "Caption for $i: "
	  if [ -z "$caption" ]
	  then
		read caption
	  else
		echo "$caption"
	  fi
    else
      caption=""
    fi

    if [ -z "$THUMBSONLY" ]
    then
	  echo "<a href=\"$i\"><img src=\"$thumb\">&nbsp;$caption</a><br>" >> $index
    fi
done

if [ -z "$THUMBSONLY" ]
then
  echo "<hr>" >> $index
  echo "<address>" >> $index
  echo "Waider" >> $index
  echo "</address>" >> $index
  echo "</body>" >> $index
  echo "</html>" >> $index
fi
