#!/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]"
	if [ "1" = "$DETAIL_LEVEL" ] ; then
		find -d "$1" -name "$2" -execdir rm -rfv {} \;	# debug ( verbose output )
	else
		find -d "$1" -name "$2" -execdir rm -rf {} \;	
	fi
}

# $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 "error:  !!!  remove /Library/Receipts/$1 failed   !!!\n"
#		exit 1
fi

groupDir="/var/db/receipts"
DirectoryRemoveSubset "$groupDir" "$1"
if [ $? -ne 0 ]
	then
		printf "error:  !!!  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 
MANUFACTURER="Samsung"
PRODUCT="ICDM"
FULL_SOFTWARE_PRODUCT_NAME="$MANUFACTURER $PRODUCT"

###### parse parameters

# command line
THIS_SCRIPT_PATH=$0
THIS_SCRIPT_SHORT_NAME=`basename "$THIS_SCRIPT_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 install $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


###### start timestamp
TIME_BEGIN=`date +%s`
echo "$FULL_SOFTWARE_PRODUCT_NAME Uninstall - started at `date`"

###### remove files
DirectoryRemoveSubset "/Library/Image Capture/Devices" "Samsung Scanner.app"

###### remove PackageMaker stuff files
ReceiptsRemove "icdmscanner*"
ReceiptsRemove "profiles.pkg"
ReceiptsRemove "com.samsung.ica.samsungScanDriver*"	
		
		
###### end timestamp
TIME_END=`date +%s`
echo
ElapsedTimePrint "$FULL_SOFTWARE_PRODUCT_NAME Uninstall - Total uninstall time:" $TIME_BEGIN $TIME_END

