#!/bin/bash

# **************************************************************
#
# This script resizes pictures.
# The original pictures are not changed.
# Dependency: Uses convert from the ImageMagick suite.
#
# This script is licensed under GPL version 2 or any subsequent
# version at your choice.
# Copyright 2008 by Michael N. Steen
#
# Use at your own risk. There is no warrenty for anything at all
# except using space on your harddisk.
#
# **************************************************************

# default values
ext="jpg"
out="jpg"
pre="w"
size="700x400"
#filename='*'
subdir="small"
verbose="false"
testrun="false"
# read arguments

if [ "$#" -gt 0 ]; then
while [ "$#" -gt 0 ]
do
  case "$1" in
    -e|--ext   )	ext="$2"
			shift  ;;
    -o|--out   )	out="$2"
			shift  ;;
    -s|--size  )	size="$2"
			shift  ;;
    -d|--dir   )	subdir="$2"
			shift  ;;
    -p|--pre   )	pre="$2"
			shift  ;;
    -v|--verbose )	verbose="true" ;;
    --test     )	testrun="true" ;;
    -?|--help  )	
    		echo "A number of options may be used. Defaults are given in brackets."
    		echo " -e --ext	 : Input file extension [$ext]"
    		echo " -o --out	 : Output file extension [$out]"
    		echo " -s --size : Max size of pictures for web [$size]"
    		echo " -d --dir  : Where to place pictures and html files [$subdir]"
    		echo " -p --pre  : Prefix to apply to picture files [$pre]"
    		echo " -v --verbose : Tell what you are doing [$verbose]"
   		echo " --test    : Testrun. Don't convert pictures [$testrun]"
		exit 0
		;;
  esac
  shift
done
fi

if [ "$verbose" = "true" ]; then
  echo " Input file extension: [$ext]"
  echo " Output file extension: [$out]"
  echo " Max size of pictures: [$size]"
  echo " Where to place pictures: [$subdir]"
  echo " Prefix to apply to picture files [$pre]"
  echo " Tell what you are doing: [$verbose]"
  echo " Testrun. Don't convert pictures: [$testrun]"
fi

total=`ls | grep $ext | wc -w`
if [ "$total" -eq 0 ]; then
  echo "No input files"
  exit 128
fi

pics=*."$ext" # `ls *.$ext`
first=true
picno=0

if [ "$verbose" = "true" ]; then
  if [ -e "$subdir" ]; then
    echo "Using already existing directory: "$subdir""
  else
    echo "Making directory: "$subdir""
  fi
fi
if [ ! -e "$subdir" ] && [ ! "$testrun" = "true" ]; then
  mkdir "$subdir"
fi
for f in $pics
do # make resized pictures
  fname=${f%.*}    # fjern filtype (.jpg, .png ..)
  if [ "$verbose" = "true" ]; then
    echo -n "Processing picture $pre$fname ... "
  fi
  if [ ! "$testrun" = "true" ]; then
    convert $f -resize $size "$subdir"/$pre$fname.$out
  fi
  if [ "$verbose" = "true" ]; then
    echo "done."
  fi
done
