#!/bin/bash
#
# This script will resize a batch of files (be carefull the original images will be altered)
#
# @version	1.0.0
# @author	Tijs Verkoyen <tijs@sumocoders.be>

# check if convert exists
if ! which "convert" > /dev/null; then
	echo "convert isn't available, check if imagick is installed."
	exit 1
fi

# get options
while getopts "w:h:" OPTIONS; do
	case "$OPTIONS" in
		w) 
			WIDTH="$OPTARG"
			;;
		h) 
			HEIGHT="$OPTARG"
			;;
		\?)
			echo "Invalid option: $OPTARG"
			exit 1
			;;
	esac
done

# clear all options
shift $(( OPTIND -1 ))

# needed options provided
if [[ -z "$WIDTH" && -z "$HEIGHT" ]] ; then
	# output usage
	echo "Usage: batch_resize [-hw] <directory>" 
	echo "-h	height, the new height for the images"
	echo "-w	width, the new width for the images"
	
	# stop the script
	exit 1
fi

# check width
if [[ -n "$WIDTH" && $WIDTH != [0-9]* ]]; then
	# warn the user
	echo "Invalid width"
	
	# stop the script
	exit 1
fi

# check height
if [[ -n "$HEIGHT" && $HEIGHT != [0-9]* ]]; then
	# warn the user
	echo "Invalid height"
	
	# stop the script
	exit 1
fi

if [ -z $1 ]; then
	PATH=`cd ./; pwd`
else
	PATH=`cd $1; pwd`
fi

# build size
SIZE=""

# append width if provided
if [[ -n "$WIDTH" ]]; then
	SIZE=$WIDTH
fi

# append height if povided
if [[ -n "$HEIGHT" ]]; then
	SIZE=$SIZE"x"$HEIGHT
fi

# when both are provided we want the aspect ratio to be ignored
if [[ -n "$WIDTH" && -n "$HEIGHT" ]]; then
	SIZE=$SIZE"!"
fi

# loop files
for FILE in "$PATH"/*
do
	# build the command
	CMD="/usr/local/bin/convert -resize $SIZE $FILE $FILE"
	
	# execute
	$CMD
done

# tell the user we are done.
echo "Done"