#!/bin/sh -Cefu


set -Cefu


_img_size()
{
	local file="$1"
	
	
	exiftool -n -json -Orientation -ImageWidth -ImageHeight "$file" \
	| jq '.[] | .Orientation, .ImageWidth, .ImageHeight' \
	| xargs echo | awk '{ if ($1 ~ /^[68]$/) { print $3 " " $2 }
	else { print $2 " " $3 } }' | xargs printf 'width="%s" height="%s"'
}


_img()
{
	local imgs="$1"
	local img resized convert_extra_options filetype
	
	
	echo '<p>'
	echo
	
	
	for img in $imgs
	do
		convert_extra_options=
		
		
		case "$img" in *-resized.*) continue ;; esac
		
		
		filetype="`exiftool -s3 -FileType \"$img\" 2> /dev/null || :`"
		
		
		case "$filetype"
		in
			JPEG)
				#convert_extra_options='-sampling-factor 4:2:0
				#-strip -quality 85 -interlace Plane
				#-gaussian-blur 0.05 -colorspace RGB
				#-auto-orient'
				;;
			
			PNG) ;;
			
			*) continue ;;
		esac
		
		
		resized="`echo \"$img\" | sed 's|\.|-resized.|'`"
		
		
		convert "$img" -resize 375x $convert_extra_options "$resized"
		
		
		cat <<- eof
		<a href="$img">
		<img src="$resized" alt="$resized"
		`_img_size "$resized"` fetchpriority="high">
		</a>
		
		eof
	done
	
	
	echo '</p>'
}


case "${1:-}"
in
	p)
		cat <<- eof
		<p>
		
		</p>
		eof
		;;
	a)
		case "${2:-}"
		in
			'')
				cat <<- eof
				<a href=""></a>
				eof
				;;
			*)
				cat <<- eof
				<a href="$2">$2</a>
				eof
				;;
		esac
		;;
	pre)
		case "${2:-}"
		in
			'')
				cat <<- eof
				<pre></pre>
				eof
				;;
			-)
				echo '<pre>'
				
				sed 's|<|\&lt;|g; s|>|\&gt;|g'
				
				echo '</pre>'
				;;
		esac
		;;
	img)
		case "${2:-}"
		in
			'')
				cat <<- eof
				<a href="">
				<img src="" alt=""
				width="" height="" fetchpriority="high">
				</a>
				eof
				;;
			*)
				shift
				
				_img "$*"
				;;
		esac
		;;
esac
