#!/bin/bash
# UTshotconv, small image converter by Katja (fly5.kapsi.fi)
# made for converting ut2003 screenshots easily..

## SETTINGS ##

# DIR where the images are located
beforedir="$HOME/.ut2003/System"

# where to put the converted ones
afterdir="$HOME/Kuvat/ut2003shots"

# comment out if you don't want subfolders by date (without date will override files with the same name)
afterdir="$afterdir/`date "+%F_%H%M"`"

# prefix..
prefix="Shot"

# suffix before..
suffix="bmp"

#suffix after
new="jpg"

# should original images be removed after converting? 1 = yes
removeafter=1

## END OF SETTINGS ##

# is there directory
[[ ! -d "$beforedir" ]] && echo "No such directory: $beforedir" && exit 1

# is there images
images="$(ls $beforedir/$prefix*.$suffix 2>/dev/null)"
[[ -z "$images" ]] && echo "No images to convert. Exiting." && exit 1

# destination directory
mkdir -p "$afterdir"

counter=0
error=0

for file in $images; do
	# name with new suffix
	name="$(basename $file)"
	part="${name/%.$suffix/.$new}"
	wholenew="$afterdir/$part"

	echo "Converting $name => $part"
	# edit the convert command parameters if basic convert is not enough
	convert $file $wholenew

		# exit status and counting
		if [[ "$?" -eq "0" ]]; then
			((counter++))
		else
			((error++))
			echo "Error with: $file"
		fi
done

if [[ "$removeafter" == "1" ]]; then
	echo -n "Removing original files.."
		for remove in $images; do
			name="$(basename $remove)"
			rm "$remove" && echo -n "." || echo ".can't remove: $name"
		done
	[[ "$?" == "0" ]] && echo -n "..all clear" || echo -n "..oh no, there were some errors."
fi

echo
echo "--"
echo "Converted $counter files with $error error(s)"
echo "Files are stored in folder: $afterdir"
echo "--"

exit $?
