#!/usr/pkg/bin/bash

# Crop image
#
# Requires ImageMagick and exiftool


process_raw ()
{
	tmpdir=$(mktemp --tmpdir --directory geeqie_crop_image_XXXXXX)

	list=$(exiv2 -pp "$1")
	if [[ ! -z "$list" ]]
	then
		readarray -t split_list <<<"$list"

		array_length="${#split_list[@]}" 
		exiv2 -ep"$array_length" "$1" --location "$tmpdir"

		src_filename=$(ls "$tmpdir/")
		filename="${src_filename%.*}"
		extension="${src_filename##*.}"
		rotation=$(exiftool -Orientation -n "$1" | cut -d':' -f2 | xargs)
		convert "$tmpdir/$src_filename" -crop "$2" "$tmpdir/$filename-crop.$extension"

		exiftool -Orientation=$rotation -n "$tmpdir/$filename-crop.$extension"

		rm "$tmpdir/$src_filename"

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

	return $res
}

process_plain ()
{
	tmpdir=$(mktemp --tmpdir --directory geeqie_crop_image_XXXXXX)

	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" --width="$width" --window-icon="$window_icon"
	else
		geeqie --remote view:"$tmpdir/$filename-crop.$extension"
	fi
}

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

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

		coords=$(geeqie --remote --get-rectangle)

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

		filename=$(basename -- "$1")
		extension="${filename##*.}"

		if [ "${extension,,}" = "jpeg" ]
		then
			source_file="$1"
			process_plain "$1" $coords
		elif [ "${extension,,}" = "jpg" ]
		then
			source_file="$1"
			process_plain "$1" $coords
		elif [ "${extension,,}" = "png" ]
		then
			source_file="$1"
			process_plain "$1" $coords
		elif [ "${extension,,}" = "tif" ]
		then
			source_file="$1"
			process_plain "$1" $coords
		elif [ "${extension,,}" = "tiff" ]
		then
			source_file="$1"
			process_plain "$1" $coords
		else
			process_raw "$1" $coords
			if [ $? = 1 ]
			then
				process_plain "$1" $coords
			fi
		fi
	else
		zenity --info --title="$title" --width="$width" --height=100 --text="Crop image\n\nexiftool is not installed" --title="$title" --window-icon="$window_icon" 2>/dev/null
		exit 0
	fi
else
	zenity --info --title="$title" --width="$width" --height=100 --text="Crop image\n\nImageMagick is not installed" --title="$title" --window-icon="$window_icon" 2>/dev/null
	exit 0
fi
