#!/bin/sh

# This script requires ladon/parallel, dcraw, exiftool, and jpeg-recompress
# Usage:
#   $ cd path/to/photos
#   $ jpeg-archive
# Compressed JPEGs are now in ./Comp/*

if [ "$1" = '-h' -o "$1" = '--help' ]; then
    echo 'JPEG-Archive - Compress RAW and JPEG images in the current folder'
    echo 'Usage: jpeg-archive [options]'
    echo ''
    echo 'Possible compression options:'
    echo "$(jpeg-recompress --help | tail -n+6)"
    exit 255
elif [ "$1" = '-v' -o "$1" = '--version' ]; then
    jpeg-recompress --version
    exit 255
fi

LADON=$(command -v ladon)
PARALLEL=$(command -v parallel)

if [ -z "$LADON" -a -z "$PARALLEL" ]; then
    echo 'jpeg-archive: this script requires either Ladon or GNU Parallel'
    exit 1
fi

set -e

# Cleanup old files
rm -rf Comp /tmp/comp

if [ -n "$LADON" ]; then
	echo 'Converting RAW files...'
	"$LADON" -m /tmp/comp/RELDIR '**/*.+(cr2|nef|dng)' -- "dcraw -w -q 3 -c RELPATH | jpeg-recompress ${@:--q high} --ppm - /tmp/comp/RELDIR/BASENAME.jpg"

	echo 'Copying EXIF data...'
	"$LADON" '**/*.+(cr2|nef|dng)' -- exiftool -overwrite_original -TagsFromFile RELPATH -all:all /tmp/comp/RELDIR/BASENAME.jpg

	echo 'Recompressing JPEG files'
	"$LADON" -m /tmp/comp/RELDIR '**/*.jpg' -- jpeg-recompress ${@:--q high} RELPATH /tmp/comp/RELPATH
elif [ -n "$PARALLEL" ]; then
	echo 'Converting RAW files...'
	find . -name '*.cr2' -o -name '*.nef' -o -name '*.dng' | \
		"$PARALLEL" --no-notice "mkdir -p /tmp/comp/{//}; dcraw -w -q 3 -c {} | jpeg-recompress ${@:--q high} --ppm - /tmp/comp/{.}.jpg"

	echo 'Copying EXIF data...'
	find . -name '*.cr2' -o -name '*.nef' -o -name '*.dng' | \
		"$PARALLEL" --no-notice "exiftool -overwrite_original -TagsFromFile {} -all:all /tmp/comp/{.}.jpg"

	echo 'Recompressing JPEG files'
	find . -name '*.jpg' | \
		"$PARALLEL" --no-notice "mkdir -p /tmp/comp/{//}; jpeg-recompress ${@:--q high} {} /tmp/comp/{}"
fi

mv /tmp/comp Comp

echo 'Done! Compressed files are in the Comp folder.'
