#!/usr/pkg/bin/bash

## @file
## @brief Crop image
##
## Requires ImageMagick and exiv2
## Crops the image to the size set by the Draw Rectangle menu item
##

process_raw ()
{
	tmpdir=$(mktemp -d "${TMPDIR:-/tmp}/geeqie.XXXXXXXXXX")

	array_length=$(exiv2 -pp "$1" | wc -l)

	if [ "$array_length" -gt 0 ]
	then
		# Take last item - should be highest resolution
		exiv2 --location "$tmpdir" -ep"$array_length" "$1"

		src_filename=$(ls "$tmpdir/")
		filename="${src_filename%.*}"
		extension="${src_filename##*.}"
		rotation=$(exiv2 -g Exif.Image.Orientation -Pv "$1")
		convert "$tmpdir/$src_filename" -crop "$2" "$tmpdir/$filename-crop.$extension"

		exiv2 -M"set Exif.Image.Orientation $rotation" "$tmpdir/$filename-crop.$extension"

		rm "$tmpdir/$src_filename"

		geeqie --view="$tmpdir/$filename-crop.$extension"
		res=0
	else
		res=1
	fi

	return "$res"
}

process_plain ()
{
	tmpdir=$(mktemp -d "${TMPDIR:-/tmp}/geeqie.XXXXXXXXXX")

	src_filename=$(basename -- "$1")
	filename="${src_filename%.*}"
	extension="${src_filename##*.}"
	convert "$1" -crop "$2" "$tmpdir/$filename-crop.$extension"
	if [ $? = 1 ]
	then
		zenity --error --title="$title" --text="Cannot process this file format" --window-icon="$window_icon"
	else
		geeqie --view="$tmpdir/$filename-crop.$extension"
	fi
}

export window_icon="/usr/local/share/pixmaps/geeqie.png"
export title="Geeqie crop image"

if [ -x "$(command -v convert)" ]
then
	if [ -x "$(command -v exiv2)" ]
	then

		coords=$(geeqie --get-rectangle)

		if [ -z "$coords" ]
		then
			zenity --error --title="$title" --text="Rectangle coordinates have not been set" --window-icon="$window_icon" 2> /dev/null
			exit 0
		fi

		filename=$(basename -- "$1")
		extension=$(printf '%b' "${filename##*.}" | tr '[:upper:]' '[:lower:]')
		if [ "${extension}" = "jpeg" ]
		then
			process_plain "$1" "$coords"
		elif [ "${extension}" = "jpg" ]
		then
			process_plain "$1" "$coords"
		elif [ "${extension}" = "png" ]
		then
			process_plain "$1" "$coords"
		elif [ "${extension}" = "tif" ]
		then
			process_plain "$1" "$coords"
		elif [ "${extension}" = "tiff" ]
		then
			process_plain "$1" "$coords"
		else
			process_raw "$1" "$coords"
			if [ $? = 1 ]
			then
				process_plain "$1" "$coords"
			fi
		fi
	else
		zenity --info --title="$title" --text="Crop image\n\nexiv2 is not installed" --title="$title" --window-icon="$window_icon" 2> /dev/null
		exit 0
	fi
else
	zenity --info --title="$title" --text="Crop image\n\nImageMagick is not installed" --title="$title" --window-icon="$window_icon" 2> /dev/null
	exit 0
fi

