#!/usr/bin/env bash

#
# Applies color profile for CanoScan LiDE 700F to RGB images scanned with this scanner
# Run for each file in a directory of images using a for loop in bash
# Last updated April 19, 2019
#
#

if [ ! -f /Users/david/Public/Canon\ MP480.icc ]; then
    echo "ERROR: Could not find color profile at /Users/david/Public/Canon MP480.icc, exiting"
	exit 1
fi

for FILE in "$@"
do
	echo "Processing $FILE:"
	
  if echo "$FILE" | grep -qi "\.TIFF\|\.TIF\|\.JPEG\|\.JPG\|\.PNG"; then
		echo "- Can process this file type"
	else
		echo "- Don't know what to do with this file type, skipping"
		continue
	fi

	if [[ $FILE == *"_original"* ]]; then
	  echo "- Already processed $FILE, done"
	  continue
	fi

  exiftool "$FILE" > /tmp/exiftooloutput

  # Check if scanned with Image Capture, i.e. if the photo has been scanned
  if cat /tmp/exiftooloutput | grep -q "Image Capture"; then
    echo "- Created with Image Capture"
    # Check that the image is RGB (not grayscale)
		if cat /tmp/exiftooloutput | grep -q "Color Space Data                : RGB\|Color Space                     : sRGB\|Color Type                      : RGB\|Photometric Interpretation      : RGB"; then
			echo "- Colorspace is RGB"
      # At this point, convert PNG files to TIFF if necessary (better ICC support)
			if [[ $FILE == *".png"* ]]; then
			  echo "- Converting from PNG to TIFF"
			  convert "$FILE" "${FILE%.*}.tiff" || continue
			  exiftool -overwrite_original_in_place -tagsFromFile "$FILE" "${FILE%.*}.tiff" && rm "$FILE"
			  FILE="${FILE%.*}.tiff"
			fi
      # Was the image scanned with our MP480?
    	if cat /tmp/exiftooloutput | grep -q "Camera Model Name               : MP480 series\|Camera Model Name               : Canon MP480 series"; then
    		echo "- Scanned with MP480"
  			if cat /tmp/exiftooloutput | grep -q "Profile Description             : Canon MP480"; then
  				echo "- Already has MP480 color profile, done"
  			else
  				echo "- Applying MP480 color profile..."
  				exiftool '-ICC_Profile<=/Users/david/Public/Canon MP480.icc' "$FILE"
  			fi
      # Was it scanned with the LiDE 700F?
      elif cat /tmp/exiftooloutput | grep -q "Camera Model Name               : LiDE 700F"; then
		    echo "- Scanned with LiDE 700F"
  			if cat /tmp/exiftooloutput | grep -q "Profile Description             : CanoScan"; then
  				echo "- Already has CanoScan color profile, done"
  			else
  				echo "- Applying CanoScan color profile..."
  				exiftool '-ICC_Profile<=/Users/david/Public/CanoScan LiDE 700F.icc' "$FILE"
  			fi
      fi
    else
      echo "- Not RGB (likely grayscale)"
    fi
  else
    echo "- Not created with Image Capture, probably not scanned"
  fi

	rename 's/(\.[a-z][a-z][a-z]+)_original/_original$1/' "${FILE%.*}"*
done