#!/bin/bash
#
# convert any image (essentially from AdobeRGB or CMYK) to sRGB jpg
# and optionally resize
#
#
# From a IM Forum discussion...
# http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=16464&start=15
#
# Author: 25albert at gmail, "mivk", 26 June 2010, Feb. 2012, July 2012, Oct. 2016
#
###

## fixme: add_options is not really used, or not consistently. fix or suppress

VERSION=0.28

# default profile file names
# apt-get install icc-profiles imagemagick
srgb=sRGB.icm
cmyk=ISOwebcoated.icc

# defaults
profile_dir=/usr/share/color/icc
outdir=.
debug=
log=

quiet="-quiet"

## Define functions
Usage() {
	cat <<END_HELP;
Usage: $0 [options] INFILE [OUTFILE]
Options:
	-h			  Print this help
	-d			  Print debugging info while processing
	-v			  Be verbose (same as -d for now)
	-c            Crop to force exact dimensions (needs full size with -s WxH).
	-s nnn[xhhh]  Specify new width in pixels or new size as widthxheight (ie -s 640x480)
	-x            Do NOT enlarge smaller images when resizing
	-a "im options" Additional options for IM
	-p profile_dir  Path to profile directory with icc/icm files
	-o dir		  Output directory
	-l log		  Log file
END_HELP
}

die() {
	echo "$1" 1>&2
	exit 1;
}


## Read options
while getopts "dvchxo:s:a:p:l:" opt
do
  case $opt in
		"d"   ) debug=1;; # verbose is same as debug for now
		"v"   ) debug=1;; # verbose is same as debug for now
		"c"   ) crop=1;;
		"s"   ) size=$OPTARG;;
		"x"   )	[[ "$size" =~ x ]] || size="${size}x"; size="$size\>";; ## Fixme: incompatible with crop. Will not crop if smaller
		"o"   ) outdir=$OPTARG;;
		"a"   ) add_options=$OPTARG;;
		"p"   ) profile_dir=$OPTARG;;
		"l"   ) log=$OPTARG;;
		"h"   ) Usage; exit 0;;
  esac
done
shift $(($OPTIND - 1))

f="$1"
outfile="$2"

[ -r "$f" ] || die "ERROR: cannot read file '$f'"



if [ -n "$crop" ]; then
	if [[ ! "$size" =~ [0-9]x[0-9] ]]; then
		die "Crop requires full size Width x Height. For ex: ' -c -s 1600x900 '"
	fi
	resize="-resize $size^ -gravity center -crop $size+0+0 +repage"
else
	if [ -n "$size" ]; then
		resize="-resize $size"
	else
		resize=
	fi
fi

if [ -n "$profile_dir" ]; then
	srgb="$profile_dir/$srgb"
	cmyk="$profile_dir/$cmyk"
fi

if [ ! -r "$srgb" ] || [ ! -r "$cmyk" ] ; then
	die "Missing profile files $srgb and/or $cmyk"
fi

shopt -s nullglob

# skip if not jpeg or tiff
#[[ "$f" =~ '\.(jpe?g|tiff?)$' ]] || continue

dir=$(dirname "$f")
name=$(basename "$f")
base=${name%.*}

profile="/tmp/$base.icc"

if [ -z "$outfile" ]; then
	outfile="$outdir/$base-x$size.jpg"
else
	outdir=$(dirname "$outfile")
fi

[ -d "$outdir" ] || mkdir -pv "$outdir"

if [ -n "$log" ]; then
	echo "====== $0 v. $VERSION `date` ======" | tee -a $log
	echo "f = $f" | tee -a $log
	echo "out = $outfile" | tee -a $log
	echo "outdir = $outdir" | tee -a $log
	echo "srgb = $srgb" | tee -a $log
	echo "cmyk = $cmyk" | tee -a $log
fi

[ -n "$debug" ] && echo "	resize = $resize"  | tee -a $log

# extract possible color profile
[ -n "$debug" ] && echo "	extracting profile from $f" | tee -a $log
convert $quiet "$f" "icc:$profile" 2>/dev/null

if cmp -s "$profile" "$srgb" ; then
	issrgb=true
elif [ ! -s "$profile" ]; then
	# assume srgb if no embedded profile
	issrgb=true
else
	issrgb=false
fi

if identify $quiet -format "%r" "$f" | grep CMYK >/dev/null ; then
	iscmyk=true
else
	iscmyk=false
fi

if ! $iscmyk && [ -z "$size" ] && $issrgb; then
	[ -n "$debug" ] && echo "	No change for $f" | tee -a $log
    [ -f "$profile" ] && rm "$profile"
	exit 250
fi

if [ -s "$profile" ]; then
	# we have an embedded profile, so ImageMagick will use that anyway
	[ -n "$debug" ] && echo "	convert with embedded profile $f"  | tee -a $log
	convert $quiet "$f" -profile "$srgb" +profile '*' $resize $add_options "$outfile" \
		&& echo -e "\tOK $outfile"
else
	# no embedded profile in source
	if $iscmyk ; then
		# CMYK file without embedded profile
		[ -n "$debug" ] && echo "	convert cmyk without embedded profile $f" | tee -a $log
		convert $quiet "$f" -profile "$cmyk" -profile "$srgb" $resize $add_options "$outfile" \
			&& echo -e "\tOK $outfile"
	else
		# No profile and not CMYK. Probably already in RGB. Just resize
		[ -n "$debug" ] && echo "	resizing only $f" | tee -a $log
		convert $quiet "$f" $resize $add_options "$outfile" \
			&& echo -e "\tOK $outfile"
	fi
fi

[ -f "$profile" ] && rm "$profile"
