#!/bin/sh
# copy .icc files to MacOS 10.5, 10.6 and higher
################################

function CopyNonExecutable()
{
	cp -f  "${sourceFolder}/${fileName}" "${destinationFolder}"
	resultCode="$?"
	if [ "$resultCode" -ne 0 ]
	then
		echo "cannot copy ${sourceFolder}/${fileName} to ${destinationFolder}."
		return $resultCode
	fi

	chown -R root:admin "${destinationFolder}/${fileName}"
	resultCode="$?"
	if [ "$resultCode" -ne 0 ]
	then
		echo "cannot set ownership on ${destinationFolder}/${fileName}."
		return $resultCode
	fi

	chmod 0664 "${destinationFolder}/${fileName}"
	resultCode="$?"
	if [ "$resultCode" -ne 0 ]
	then
		echo "cannot set permissions on ${destinationFolder}/${fileName}."
		return $resultCode
	fi

	return 0
}

function DirectoryRemoveSubset()
{
	echo "DirectoryRemoveSubset [$2] from [$1]"
	find -d "$1" -name "$2" -execdir rm -rfv {} \;	
}

################################
thisScriptPath="$0"
packagePath=$1
targetLocation=$2
targetVolume=$3

echo "thisScriptPath  ${thisScriptPath}."
echo "packagePath  ${packagePath}."
echo "targetLocation  ${targetLocation}."
echo "targetVolume  ${targetVolume}."

applicationTitle=`defaults read "${packagePath}/Contents/Info" AppTitle -string`
applicationTitleFirstLetterLoverCase=`echo ${applicationTitle:0:1} | tr "[A-Z]" "[a-z]"`
applicationTitleCamelCase=`echo $applicationTitle | sed -e "s/ //g" -e "s/^./$applicationTitleFirstLetterLoverCase/g"`


destinationFolder="/Library/Image Capture/Devices/${applicationTitle}.app/Contents/Resources"



################################
echo "Installing ICC files..."

destinationFolder2="/tmp/__ICDM_PM_ICC_${applicationTitleCamelCase}__"
echo "restoring saved icc from $destinationFolder2 to $destinationFolder..."
#find "$destinationFolder2" -name '*.icc' -type f -exec sh -c 'exec mv -f "$@" "$destinationFolder"' inline {} +
cd "$destinationFolder2"
ls *.icc | cpio -o | (cd "${destinationFolder}"; cpio -i -m)
DirectoryRemoveSubset "${destinationFolder}2" "${destinationFolder}"
#ignore result


sourceFolder2="$packagePath/../../Resources"

echo "copying icc from $sourceFolder2 to $destinationFolder..."

#find "$sourceFolder2" -name '*.icc' -type f -exec sh -c 'exec cp -f "$@" "/Library/Image Capture/Devices/Samsung Scanner.app/Contents/Resources"' inline {} +
#find "$sourceFolder2" -ls -name '*.icc' -type f -exec sh -c 'exec cp -v -f "$@" "/Library/Image Capture/Devices/Samsung Scanner.app/Contents/Resources"' inline {} +
cd "$sourceFolder2"
ls *.icc | cpio -o | (cd "${destinationFolder}"; cpio -i -m)

resultCode="$?"
if [ "$resultCode" -ne 0 ]
then
	echo "copying .icc failed"
	exit 1
fi

find "$destinationFolder" -name "*.icc" -exec chown -R root:admin {} \;
resultCode="$?"
if [ "$resultCode" -ne 0 ]
then
	echo "cannot set ownership"
	exit 1
fi

find "$destinationFolder" -name "*.icc" -exec chmod 0664 {} \;
resultCode="$?"
if [ "$resultCode" -ne 0 ]
then
	echo "cannot set permissions"
	exit 1
fi

echo "OK."
