#!/bin/bash

#$1 is url to source image

#$2 is optional url to destination image to be diffed with $1

cd /tmp;
string="$(curl -O -J -s -w "%{filename_effective}, %{http_code}" $1)";
#https://stackoverflow.com/a/45201229/1201238

function mfcb { local val="$4"; "$1"; eval "$2[$3]=\$val;"; };
function val_ltrim { if [[ "$val" =~ ^[[:space:]]+ ]]; then val="${val:${#BASH_REMATCH[0]}}"; fi; };
function val_rtrim { if [[ "$val" =~ [[:space:]]+$ ]]; then val="${val:0:${#val}-${#BASH_REMATCH[0]}}"; fi; };
function val_trim { val_ltrim; val_rtrim; };
readarray -c1 -C 'mfcb val_trim a' -td, <<<"$string,"; unset 'a[-1]'; declare -p a > /dev/null;
filename="${a[0]}"
status="${a[1]}"
if [[ $status = "200" ]]; then
	type="$(identify -format %[magick] ${filename})";
	if [[ $type = PNG ]]; then
		convert -strip "$filename" -fuzz 10% -trim +repage "$filename";
	elif [[ $type = JPEG ]]; then
		jpegtran -perfect -copy none -trim -optimize -crop $(convert "$filename" -fuzz 10% -trim -format "%wx%h%X%Y" info:-) -outfile "$filename" "$filename";
	fi

	if [ -z "$2" ]; then
		echo "/tmp/$filename";
		identify -format "%wx%h" "/tmp/$filename"

	else
		string2="$(curl -O -J -s -w "%{filename_effective}, %{http_code}" $2)";
		readarray -c1 -C 'mfcb val_trim a' -td, <<<"$string2,"; unset 'a[-1]'; declare -p a > /dev/null;
		filename2="${a[0]}"
		status2="${a[1]}"
		if [[ $status2 = "200" || $status2 = "404" ]]; then
			#nice! cloudinary filename duplicate file extension, so no chance of overwrite due to collision

			if cmp -s "$filename" "filename2"; then
				echo "same";
			else
				echo "/tmp/$filename";
				identify -format "%wx%h" "/tmp/$filename"

			fi

		else
			echo "$status2";
		fi

	fi

else
	echo "$status";
fi