#!/bin/sh


################################## helper functions

# $1 - full path to source directory (directory itself not copied)
# $2 - wildcard or file/dir name
function DirectoryRemoveSubset()
{
	echo "DirectoryRemoveSubset [$2] from [$1]"
	find -d "$1" -name "$2" -execdir rm -rfv {} \;	
#	find "$1" -name '$2' -delete	
}

# $1 - message
# $2 - start time as in `date +%s`
# $3 - end time as in `date +%s`
function ElapsedTimePrint()
{
_elapsed=`expr $3 - $2`
_elapsed_min=`expr $_elapsed / 60`
_elapsed_sec=`expr $_elapsed % 60`

echo "$1 $_elapsed s ($_elapsed_min min $_elapsed_sec s)."
}


# $1 - package name; wildcards allowed
function ReceiptsRemove()
{
groupDir="/Library/Receipts"
DirectoryRemoveSubset "$groupDir" "$1"
if [ $? -ne 0 ]
	then
		printf "warning:  !!!  remove /Library/Receipts/$1 failed   !!!\n"
#		exit 1
fi

groupDir="/var/db/receipts"
DirectoryRemoveSubset "$groupDir" "$1"
if [ $? -ne 0 ]
	then
		printf "warning:  !!!  remove /var/db/receipts/$1 failed   !!!\n"
#		exit 1
fi
}


################################## main script body


#### set up itself

# set to 1 for debugging
DETAIL_LEVEL=0

# global variables 

FULL_SOFTWARE_PRODUCT_NAME="ScanThru"

#### parse parameters

# command line
THIS_SCRIPT_PATH=$0
THIS_SCRIPT_SHORT_NAME=`basename "$THIS_SCRIPT_PATH"`
THIS_SCRIPT_DIRECTORY=`dirname "$THIS_SCRIPT_PATH"`


# echo
# _lastModificationTime=`stat -f "%Sm" "$0"` #`stat -c "%z" "$0"` # `find "$0" -printf "%t"` #
# echo "** SRC Mac Fax Package Maker uninstall procedure of $_lastModificationTime **"
# echo
# echo "PATH:"
# echo $PATH

# check user permissions
MY_UID=`/usr/bin/id -u`
if [ "$MY_UID" != "0" ]
then
	echo
	echo "You should have root privileges in order to uninstall $FULL_SOFTWARE_PRODUCT_NAME."
	echo "Please login as root or use an utility 'su' or 'sudo' when you run $THIS_SCRIPT_PATH." 
	if [ "1" = "$DETAIL_LEVEL" ] ; then
		echo "Current UID: $MY_UID."
	fi		
	exit 2
else
	if [ "1" = "$DETAIL_LEVEL" ] ; then
		echo "root UID: $MY_UID."
	fi		
fi

###### print date
TIME_BEGIN=`date +%s`
echo "Started at `date`"


###### remove the files from directories for different destinations and conditions
packageResourcesDir="$THIS_SCRIPT_DIRECTORY/ScanThru Installer.mpkg/Contents/Packages/libictds.pkg/Contents/Resources/1"
bundleName=`cat "$packageResourcesDir/Info.plist" | grep CFBundleName -A1 | tail -1 | sed 's.*<string>' | sed 's</string>' | awk '{print $0}' | tr -d "\r"`


groupDir="/Library/Image Capture/TWAIN Data Sources"
DirectoryRemoveSubset "$groupDir" "$bundleName"
if [ $? -ne 0 ]
	then
		printf "warning:  !!!  remove [$bundleName] from [$groupDir] failed   !!!\n"
#		exit 1
fi

###### remove PackageMaker stuff files
ReceiptsRemove "com.src.ScanThru.*"
ReceiptsRemove "libictds.*"
ReceiptsRemove "dummy.*"

#echo "CUPS on..."
#cupsStart

###### print date
TIME_END=`date +%s`
echo
ElapsedTimePrint "$FULL_SOFTWARE_PRODUCT_NAME Uninstall - Total uninstall time:" $TIME_BEGIN $TIME_END

