#!/bin/bash
#			/usr/local/bin/imagescape
# https://crystalfaeries.net/posix/bin/imagescape
# celeste:crystalfaery IMAGESCAPE 2021-05-13 21:29:08+00:00
# from Dave Taylor http://www.linuxjournal.com/content/resizing-images-imagemagick
# arguments are image directory paths to process (default is cwd)
# output is images sorted into	portrait  and	landscape	subfolders
# default:  leaving the whole collection also in	containing folder
# -d option removes the whole collection from		containing folder
#   leaving   only  the split collection in	landscape+portrait folders
# -i option shall run igal2 on each directory containing image files
# -i must follow -d if both specified, until we recode :-(
let help=12 # line number -1

# DEVELOPMENT INTENT: we would like to add a new feature,
# that imagescape can be extended to work recursively,
# and that as it descends a directory structure,
# it looks for files which may control the recursion,
# .include and .exclude, in the format of rsync.
# or as with name_tidy's local run_cotrol files.

# While we're hacking new code, we should do some sanity checks
# to NOT produce landscape or portrait subdirectories within
# a landscape or portrait directory, and if we do find such,
# we should intelligently correct the situation.
# An obvious step in that direction, is to DEFAULT to
# auto excluding landscape and portrait directories from recursion,
# yet some luser may manually create such a mess without our help :-)

# VERSION
if [ "${1}" = "-v" ]
then	# treat it as a version request
	head -n 4 $0 | tail -n 1
	exit
fi
if [ "${1}" = "--version" ]
then	# treat it as a version request
	head -n 4 $0 | tail -n 1
	exit
fi

# HELP
if [ "${1}" = "-h" ]
then	# treat it as a help request
	head -n ${help} $0
	exit
fi
if [ "${1}" = "--help" ]
then	# treat it as a help request
	head -n ${help} $0
	exit
fi

# DELETE option
if [ "${1}" = "-d" ]
then	# we are to remove imagedir level images once sorted into subdirs
	true;	let delete=$?	# user selected deletion of images in imagedir
	shift	# done with the option, toss it.
else	# we are to leave  imagedir level images in place
	false;	let delete=$?	# default to non deletion of images in imagedir
fi

# igal2 option
if [ "${1}" = "-i" ]
then	# we are to igal2 each directory
	true;	let igal=$?	# user selected igal2 of each directory
	shift	# done with the option, toss it.
else	
	false;	let igal=$?
fi

if	[ $# -eq 0 ]
then	# default to only launchdir since no dir argument provided
    true; if [[ $? == "${delete}" ]]
    then
	true; if [[ $? == "${igal}" ]]
	then
		exec $0 -d -i	"`pwd`"	# relaunch  with cwd  as argument
	else
		exec $0 -d	"`pwd`"	# relaunch  with cwd  as argument
	fi
    else
	true; if [[ $? == "${igal}" ]]
	then
		exec $0 -i	"`pwd`"	# relaunch  with cwd  as argument
	else
		exec $0		"`pwd`"	# relaunch  with cwd  as argument
	fi
    fi
    echo "exec returned? really?"	1>&2
    exit	-1	# splain to me how dis happen?
fi

# SORT IMAGES for each directory specified or defaulted
while	[ $# -ne 0 ]
do
    imagedir="${1}"				# where are we to work?
    shift					# prepare for Next Iteration
    cd -P "${imagedir}" || exit 1		# enter the specified image directory if can
    find ./ -type f -size 0 -exec rm {} \;	# expunge deleted files
    mkdir -p	portrait			# default if image is exactly square
    mkdir -p	landscape			# only those wider than high
    name_tidy	-r				# name_tidy in case new files were added

# copy pre-sorted-level images up into image directory
    rsync -auvH {portrait,landscape}/*.{gif,jpg,png,svg,webp} .	2>/dev/null 1>/dev/null
    rm {portrait,landscape}/{.indextemplate2.html,.slidetemplate2.html,.tile.png,.thumb_*,{????,???,??,?}.html,*.{gif,jpg,png,svg,webp}}	2>/dev/null
    rm			    {.indextemplate2.html,.slidetemplate2.html,.tile.png,.thumb_*,{????,???,??,?}.html}		2>/dev/null
    for image in `find . \! -name '.thumb_*'	\(	\
	\( -name '*.gif'	-print  \) -o	\
	\( -name '*.jpg'	-print  \) -o	\
	\( -name '*.png'	-print  \) -o	\
	\( -name '*.svg'	-print  \) -o	\
	\( -name '*.webp'	-print  \)	\)	| sed 's/^\.\///'`
    do
	identity="`identify  ${image}	|	head -n 1`"
	let result=$?
	if [[ $result -eq 0 ]]
	then	# successful identification of geometry
		 let width="`echo -e ${identity} | cut -d\   -f3 | cut -dx -f1`"
		let height="`echo -e ${identity} | cut -d\   -f3 | cut -dx -f2`"
		if [[ $width -le $height ]]
		then
			ln	"${image}"	portrait/"${image}"	|| exit 2
		else
			ln	"${image}"	landscape/"${image}"	|| exit 3
		fi
	else	# a broken file
		echo "$0: identify:$result ${image}"
		exit $result	# yo, user... you figure it out!
	fi
    done

# delete top-level images?
    true; if [[ $? == "${delete}" ]]
    then	# delete option
	cd portrait	&& for f in *.{gif,jpg,png,svg,webp};do rm ../"${f}" 2>/dev/null;done
	true; if [[ $? == "${igal}" ]]
	then
		cp /dev/null index.html
		igal2
		cat HEADER.html index.html README.html > /tmp/$$.txt
		cat /tmp/$$.txt > index.html
	fi
	cd	"${imagedir}"
	cd landscape	&& for f in *.{gif,jpg,png,svg,webp};do rm ../"${f}" 2>/dev/null;done
	true; if [[ $? == "${igal}" ]]
	then
		cp /dev/null index.html
		igal2
		cat HEADER.html index.html README.html > /tmp/$$.txt
		cat /tmp/$$.txt > index.html
	fi
	cd	"${imagedir}"
    else	# no delete
	true; if [[ $? == "${igal}" ]]
	then
	cd	"${imagedir}"/portrait || exit -1
		cp /dev/null index.html
		igal2
		cat HEADER.html index.html README.html > /tmp/$$.txt
		cat /tmp/$$.txt > index.html
	cd	"${imagedir}"/landscape || exit -1
		cp /dev/null index.html
		igal2
		cat HEADER.html index.html README.html > /tmp/$$.txt
		cat /tmp/$$.txt > index.html
	cd	"${imagedir}"
	fi
    fi	# end delete option processing
    true; if [[ $? == "${igal}" ]]
    then
	cp /dev/null index.html
	cat HEADER.html index.html README.html > /tmp/$$.txt
	cat /tmp/$$.txt > index.html
	igal2
    fi
    fdedupe -f	# de-duplicate via hardlinking
    touch index.html	# the sign to galleries script we're current in this dir
# completed current argument, are there more?
done
exit	$?
