#!/bin/sh
#  
TM_LOG_DIR=/var/log/TrendMicro
if [ -d "${TM_LOG_DIR}" ]; then
	DBGLOG="${TM_LOG_DIR}/TMSMIntegrityCheck.log"
else
	DBGLOG=/tmp/TMSMIntegrityCheck.log
fi

TRUE=1
FALSE=0

SED=/usr/bin/sed
LS=/bin/ls
WC=/usr/bin/wc

bIsUpgradeCase=0
LOCKFILE=/var/tmp/tmccupgrade.lock

if [ -e "$LOCKFILE" ]; then
    bIsUpgradeCase=1
else
    bIsUpgradeCase=0
fi

chk_os_version_tiger()
{
    OSVER=`sw_vers | grep 'ProductVersion:' | grep -o '[0-9]*\.[0-9]*\.[0-9]*'`

    cv="`echo $OSVER | cut -d'.' -f2`"
    #Special case for 10.4 & product update via AU
    if [ "$cv" = "4" ]; then
        if [ -e "$LOCKFILE" ]; then
            #Update via AU
            echo "Update on 10.4 via AU..."  >> $DBGLOG
        else 
            #Update on 10.4 from UI or Terminal
            echo "Update on 10.4 from UI or Terminal - swap true-false value"  >> $DBGLOG 
            TRUE=0
            FALSE=1
        fi
    fi
    return 0;
}

chk_and_restore_file_permission()
{
    iPermission="$1"
    filePath="$2"
    if [ ! -e "$filePath" ] || [ -z "$iPermission" ]; then
        echo "File does not exist ($filePath) Or Invalid permission parameter ($iPermission)" >> $DBGLOG
        return 1;
    fi
    
    echo "Check file permission for: $filePath" >> $DBGLOG
    #Check permission attribute for preinstall script file
	if [ ! -x "$filePath" ]; then 
		echo "Restore executable permission to script file: $filePath" >> $DBGLOG
		chmod "$iPermission" "$filePath"
		if [ $? -ne 0 ]; then
			echo "Could not restore permission to script file." >> $DBGLOG
			return 1;
		fi	
	fi
	return 0;
}

chk_mpkg_integrity()
{
    CUR_DIR=`dirname $0`
    TMCC_UPDATEDEST="${CUR_DIR}/../../../"
	ProductPkg="${TMCC_UPDATEDEST}/tmsminstall.mpkg"
    if [ $bIsUpgradeCase -eq 1 ]; then
        TMCC_UPDATEDEST="/Library/Application Support/TrendMicro/common/lib/AUlib/tmp/Product/"
		if [ `$LS -ld "${TMCC_UPDATEDEST}/"*.[mM][Pp][Kk][Gg] 2>/dev/null|${WC} -l` -eq 1 ]; then
			ProductPkg=`$LS -d "${TMCC_UPDATEDEST}/"*.[mM][Pp][Kk][Gg] 2>/dev/null|$SED -e 's/^[ 	]*//g' -e 's/[ 	]*$//g'`    
		fi
    fi
    
	echo "ProductPkg: $ProductPkg" >> $DBGLOG ;

	[ -z "$ProductPkg" ]&&return

	for i in preupgrade postupgrade preinstall postinstall preflight postflight integritycheck tmccinstcheck confcheck; do
		find "$ProductPkg" | grep "\/$i\$" | (while read fn ; do chk_and_restore_file_permission 755 "$fn" ; 
		iRet=$?
		if [ $iRet -ne 0 ]; then
			return 1;
		fi
		done )
	done

	return 0;
}


# main

# integrity check for installer package
chk_mpkg_integrity
if [ $? -eq 1 ]; then
	ret=$FALSE
    echo "return FALSE" >> $DBGLOG
else 
	ret=$TRUE
    echo "return TRUE" >> $DBGLOG
fi

## otherwise it is ok to continue installing 
echo "Integrity Check returns: $ret" >> $DBGLOG
exit $ret
