#!/bin/sh

relpath2abs()
{
    if [ `expr x"$1" : x'/'` -ne 0 ]; then
        rel="$1"
    else
        rel="$PWD/$1"
    fi
    
    abs="/"
    IFS='/'
    for comp in $rel; do
        case "$comp" in
        '.'|'')
            continue
            ;;
        '..')
            abs=`dirname "$abs"`
            ;;
        *)
            [ "$abs" = "/" ] && abs="/$comp" || abs="$abs/$comp"
            ;;
        esac
    done
    
    echo "$abs"
}

# OSX version check
MajorVer=`sw_vers -productVersion | cut -d'.' -f1`
MinorVer=`sw_vers -productVersion | cut -d'.' -f2`
#echo "MajorVer=$MajorVer"
#echo "MinorVer=$MinorVer"
if [ $MajorVer -ne 10 ] || [ $MinorVer -lt 7 ]; then
    # OSX version check failed
    exit 101
fi 

# User permission check
UserName=`id -un`
#echo "UserName=$UserName"
if [ "$UserName" != "root" ]; then
    # Need root permission. Please use sudo to run the script.
    exit 107
fi

# Binary folder check
BinaryDir="$1"
#echo "BinaryDir=$BinaryDir"
if [ "$BinaryDir" = "" ]; then
    # should specify binary folder
    exit 108
fi

# Convert binary folder to abs path
BinaryDirAbs=`relpath2abs "$BinaryDir"`
#echo "BinaryDirAbs=$BinaryDirAbs"
PreCheckBin="$BinaryDirAbs"/InstallPreCheck
InstallPkg="$BinaryDirAbs"/"Trend Micro Full Disk Encryption.pkg"
#echo "PreCheckBin=$PreCheckBin"
#echo "InstallPkg=$InstallPkg"

# Check InstallPreCheck file
if [ ! -x "$PreCheckBin" ]; then
    # Can not find InstallPreCheck or the file is not executable
    exit 109
fi

# Check .pkg file
if [ ! -f "$InstallPkg" ]; then
    # Can not find InstallPkg
    exit 110
fi

# Run Pre-Check
PreCheckRet=`"$PreCheckBin" checkversion`
PreCheckRet=`echo $?`
if [ $PreCheckRet -ne 0 ]; then
   # PreCheck failed
   exit $PreCheckRet
fi

# Install the .pkg
InstallPkgRet=`installer -pkg "$InstallPkg" -target /`
InstallPkgRet=`echo $?`
if [ $InstallPkgRet -ne 0 ]; then
   # Install .pkg failed
   exit 111
fi

exit 0
