#!/bin/bash

# Extract emdedded jpegs from a raw file:
#
# Display a list of the embedded files
# Extract the selected image to a tmp folder
# If jpgicc is installed, correct for currently selected rendering intent
#  and store in a new file
# Set Geeqie focus to the newly generated image

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

if [[ $count -eq 0 ]]
then
	zenity --info --width=300 --height=100 --text="Export jpeg from raw file\n\nFile contains no embedded images" --title="Geeqie export jpeg" 2>/dev/null
	exit
fi

if ! [ -x "$(command -v exiv2)" ]
then
	zenity --info --width=300 --height=100 --text="Export jpeg from raw file\n\nexiv2 is not installed" --title="Geeqie export jpeg" 2>/dev/null
	exit 1
fi

if ! [ -x "$(command -v jpgicc)" ]
then
	zenity --info --width=300 --height=100 --text="Export jpeg from raw file\n\njpgicc is not installed\ncolor corrections will not be made\nYou may install via liblcms2-utils" --title="Geeqie export jpeg" 2>/dev/null
fi

list=$(exiv2 -pp "$1")
readarray -t split_list <<<"$list"

image_list=""
n=1

for image in "${split_list[@]}"
do
	if [[ $n -eq $count ]]
	then
		image_list="$image_list"$'TRUE\n'"$image"$'\n'"$n"
	else
		image_list="$image_list"$'FALSE\n'"$image"$'\n'"$n"$'\n'
	fi
	n=$((n+1))
done

image_selected=$(echo "$image_list" | zenity  --width=500 --height=250 --title="Geeqie export jpeg" --list  --text "Select embedded image" --radiolist  --column "Select" --column "Image" --column "n" --hide-column=3 --print-column=3 2>/dev/null) 

if [[ ! -z "$image_selected" ]]
then
	tmpdir=$(mktemp --tmpdir --directory geeqie_export_jpeg_XXXXXX)

	exiv2 -ep"$image_selected" "$1" --location "$tmpdir"

	render_str=$(geeqie --remote --get-render-intent)

	case $render_str in
		"Perceptual" )
		render_key=0;;
		"Relative Colorimetric" )
		render_key=1;;
		"Saturation" )
		render_key=2;;
		"Absolute Colorimetric" )
		render_key=3;;
	esac

	filename=$(basename "$tmpdir/"* ".jpg")
	if [ -x "$(command -v jpgicc)" ]
	then
		filename_ri="$tmpdir/""$filename""-ri.jpg"
		jpgicc -t $render_key "$tmpdir/""$filename"".jpg"  "$filename_ri"

		rm "$tmpdir/""$filename"".jpg"

		geeqie --remote view:"$filename_ri"
	else
		geeqie --remote view:"$tmpdir/""$filename"".jpg"
	fi
fi
