#!/bin/bash
#                       /usr/local/bin/jpg_exif2filename
# https://crystalfaeries.net/posix/bin/jpg_exif2filename
# celeste@crystalfaeries.net  JPG_EXIF2FILENAME	2020-08-28 21:21:35+00:00
# http://langec.wordpress.com	Fix JPEG Images	2020-05-16 02:10:00 -1000
# Fix time-stamps in filenames from EXIF Date contained within JPEG photos
# http://www.commandlinefu.com/commands/view/24939/fix-time-stamped-filenames-of-jpeg-images-according-to-the-exif-date-the-photo-was-taken
# https://www.commandlinefu.com/commands/by/langec
#
# <a	href="http://www.commandlinefu.com/"
# <img	src="http://www.commandlinefu.com/images/small-logo.jpg"
# 	alt="[Command-Line Fu small Logo]"
# 	align="right" width="25%" height=""></a>
# <a	href="http://www.scriptrock.com/"
# 	>Diff your entire server config at ScriptRock.com</a>
#
#	We had to install exiv2 to support this script,
#	and in the process discovered alternatives whose names
#	begin with "exif*", and then there's renrot... ?
#
# For each *.jpg or *.JPG file IN THE CURRENT DIRECTORY,
# or instead, IN EACH OF THE DIRECTORIES LISTED AS ARGUMENTS,
# extract the date the photo was taken from its EXIF metadata;
# then replace the current date stamp embedded in the filename,
# (which is assumed to exist in the filename),	#######	or we COULD code a NON-ass-u-me
# by the date the photo was taken [can we append time?].
# A trick from https://unix.stackexchange.com/a/9256
# is used to split the date into its components. 
let help=28	# 1 less than line number within file
 
while [ $# -ne 0 ]
do
	case "${1}" in
	-v | --version )
		head -n 4 $0 | tail -n 1
		exit
		;;
	-h | --help )
		head -n $help $0
		exit
		;;
	* )	cd -P "${1}" || exit 255
		shift
		;;
	esac
	IFS=': '
	for i in *.jpg
	do
		set $(exiv2 -K 'Exif.Image.DateTime' -Pv $i 2> /dev/null); mv -v $i "$1-$2-$3${i#[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]}"
		# we SHOULD sudo touch -t YYYYMMDDHHMM $i to match filesystem date to exposure date
	done
done
