#!/bin/sh

# Compare real numbers.
function float_cond()
{
	local cond=0
	if [[ $# -gt 0 ]]; then
		cond=$(echo "$*" | bc -q 2>/dev/null)
		if [[ -z "$cond" ]]; then cond=0; fi
		if [[ "$cond" != 0  &&  "$cond" != 1 ]]; then cond=0; fi
	fi
	local stat=$((cond == 0))
	return $stat
}

function setDateVar()
{
	date_entry=$(
	date +'%Y-%m-%d %H:%M:%S')
}

# Directory path to me.
script_path=$(
cd -P -- "$(dirname -- "$0")" &&
pwd -P
) && script_path=$script_path/$(basename -- "$0")
dir_path=$(
dirname "$script_path")

# Log.
LOGFILE=$(
echo ~/Library/Logs/kerio-entourage-config-tool.log)
setDateVar
echo $date_entry Preflight script started from $dir_path. > ~/Library/Logs/kerio-entourage-config-tool.log

# Get home path.
home_dir=$(
printenv HOME)

echo $home_dir > $dir_path/homePath

# Get Mac OS X version.
ver=$(
sw_vers -productVersion | cut -d. -f1,2)
condition=$ver" >= 10.5"

# Is Microsoft Office installed?
if [ ! -d "/Library/Application Support/Microsoft" ]
then
	echo $date_entry "Cannot find /Library/Application Support/Microsoft folder. Microsoft Office does not seem to be installed." >> ${LOGFILE}
fi

# Run appropriate method according to Mac OS X version.
if float_cond $condition; then
	echo $date_entry "Running on Mac OS X 10.5 (Leopard) or higher." >> ${LOGFILE}
	
	sudo echo \#\!/usr/bin/osascript > "$dir_path/preflight.scpt"
	sudo cat "$dir_path/preflight.scpt" "$dir_path/preflight.applescript" > "$dir_path/preflight.run"
	sudo chmod 700 "$dir_path/preflight.run"
	appleScriptResult=$(
		sudo "$dir_path/preflight.run")

else
	echo $date_entry "Running on Mac OS X 10.4 (Tiger) or lower." >> ${LOGFILE}

	appleScriptResult=$(
		sudo /usr/bin/osascript "$dir_path/preflight.applescript")
fi

setDateVar

condition=$appleScriptResult" == 0"
if float_cond $condition;
then
	echo $date_entry Preflight script finished successfully. >> ${LOGFILE}
	exit 0
else
	echo $date_entry Preflight script finished with error. >> ${LOGFILE}
	exit 1
fi
