#!/bin/sh

###########################################################################
#                                                                         #
#             (C) Kerio Technologies s.r.o. All rights reserved.          #
#                                                                         #
###########################################################################

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

function setLogFiles()
{
	PY2APP_TXT_FILE=$(
	echo "$DIR_PATH""/tmp/py2app.txt")

	APP_TXT_FILE=$(
	echo "$DIR_PATH""/tmp/console.txt")
}

function getThisScriptDirPath()
{
	script_path=$(
	cd -P -- "$(dirname -- "$0")" &&
	pwd -P
	) && script_path=$script_path/$(basename -- "$0")

	DIR_PATH=$(
	dirname "$script_path")
}

function getLogFile()
{
	LOG_FILE=$(
	echo ~/Library/Logs/kerio-connect-account-assistant.log)
}

function copyPrecompiled()
{
	ver=$(
	sw_vers -productVersion)
  
	compareVersions "$ver" "10.10"

	if [ "$?" -eq 1 ]; then

	 APP_CONTENTS_DIR=$(
	 echo "$DIR_PATH""/tmp/dist/Kerio Connect Account Assistant.app/Contents")

	 if [ -f "$APP_CONTENTS_DIR"/MacOS/python ]
	 then
  	 echo SIP is disabled.
	 else
  	 echo SIP is enabled.
    
  	 setDateVar
  	 echo $DATE_ENTRY Deploying precompiled application. >> ${LOG_FILE}
  	 cp -R ../precompiled/ ../tmp/dist/
  	 ln -s /System/Library/Frameworks/ "$APP_CONTENTS_DIR"/Frameworks
  	 cp /usr/bin/python "$APP_CONTENTS_DIR"/MacOS/python
  
  	 ln -s /System/Library/Frameworks/Python.framework/Versions/2.7/include/ "$APP_CONTENTS_DIR"/Resources/include
  
  	 ln -s /System/Library/Frameworks/Python.framework/Versions/2.7/lib "$APP_CONTENTS_DIR"/Resources/lib
  
  	 mkdir -p "$APP_CONTENTS_DIR"/Resources/lib/python2.7
  
  	 mkdir "$APP_CONTENTS_DIR"/Resources/lib/python2.7/lib-dynload
  	 cp -R /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/ "$APP_CONTENTS_DIR"/Resources/lib/python2.7/lib-dynload
  
  	 cp -R /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/ "$APP_CONTENTS_DIR"/Resources/lib/python2.7/lib-dynload
  
  	 ln -s /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/email/ "$APP_CONTENTS_DIR"/Resources/lib/python2.7/email
  	 ln -s /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config/ "$APP_CONTENTS_DIR"/Resources/lib/python2.7/config
	 fi
   
	fi
}

function runPy2App()
{
	cd gui

	setDateVar
	echo $DATE_ENTRY Building application started. >> ${LOG_FILE}

	echo $DATE_ENTRY Py2app log file: $PY2APP_TXT_FILE >> ${LOG_FILE}
	# if py2app setup fails, "q" will quit started Python Pdb debugger
	echo q | python setup.py py2app --no-strip --bdist-base ../tmp/build --dist-dir ../tmp/dist | tee "${PY2APP_TXT_FILE}"
	# no exit code to check; always 0
	copyPrecompiled

	setDateVar
	echo $DATE_ENTRY Building application finished. >> ${LOG_FILE}
	cd ..
}

function printSystemInformation()
{
	echo System information >> ${LOG_FILE}
	setDateVar
	sw_vers >> ${LOG_FILE}
	python -V 2>&1 | tee -a ${LOG_FILE}
}

# Returns: 0 (=), 1 ($1>$2), 2 ($1<$2)
function compareVersions()
{
    for i in {1..2}
    do
      a="$(echo "$1" | cut -d '.' -f $i)"
      b="$(echo "$2" | cut -d '.' -f $i)"
      
      if [ -z $a ]
      then
        a=0
      fi
      
      if [ -z $b ]
      then
        b=0
      fi

      if [ $a -gt $b ]
      then
        return 1
      elif [ $a -lt $b ]
      then
        return 2
      fi
    done
    
    return 0
}

function checkSystemRequirements()
{
	ver=$(
	sw_vers -productVersion)
  
	compareVersions "$ver" "10.6"

	if [ "$?" -eq 2 ]; then
		setDateVar
		echo $DATE_ENTRY "This program requires Mac OS X 10.6 (Snow Leopard) or higher. Exiting." >> ${LOG_FILE}

		currentUser=$(ls -l /dev/console | awk '{ print $3 }')
		sudo -u ${currentUser} osascript -e 'tell application "System Events"' -e 'activate' -e 'display dialog "Account assistant requires Mac OS X 10.6 (Snow Leopard) or higher to run. Click OK to terminate the assistant." buttons {"OK"} default button 1' -e 'end tell'
		exit 1
	fi
}

function runApp()
{
	APP_FILE=$(
	echo "$DIR_PATH""/tmp/dist/Kerio Connect Account Assistant.app/Contents/MacOS/Kerio Connect Account Assistant")
	echo $DATE_ENTRY Application path: $APP_FILE >> ${LOG_FILE}

	if [ -f "$APP_FILE" ]
	then
		setDateVar
		echo $DATE_ENTRY Launching application. >> ${LOG_FILE}

		echo $DATE_ENTRY Application console log file: $APP_TXT_FILE >> ${LOG_FILE}
		"$APP_FILE" 2>&1 | tee "${APP_TXT_FILE}"

		setDateVar
		echo $DATE_ENTRY Launching finished "("exit code $?")" >> ${LOG_FILE}
	else
		echo $DATE_ENTRY Application not found. Exiting. >> ${LOG_FILE}
		currentUser=$(ls -l /dev/console | awk '{ print $3 }')
		sudo -u ${currentUser} osascript -e 'tell application "System Events"' -e 'activate' -e 'display dialog "The Assistant encountered an error that caused the setup to fail (compilation failed). Please consult /private/var/log/install.log file for more details. " & return & return & " Click OK to premature terminate the Assistant." buttons {"OK"} default button 1' -e 'end tell'
		exit 1		
	fi
}

function isLoggedRootUser()
{
	K_CONSOLE_USER="$(ls -l /dev/console |awk '{ print $3 }')"	
	if [ "$K_CONSOLE_USER" == "root" ]; then
		return 1
	else
		if [ "$USER" == "root" ]; then
			return 1
		else
			return 0
		fi
	fi
}

function zipLogs()
{
	ZIP_FILE=$(
	echo "$DIR_PATH""/tmp/results.zip")

	APP_DEBUG_LOG=$(
	echo "$DIR_PATH""/tmp/debug.log")
	
	setDateVar
	echo $DATE_ENTRY Zipping results to: $ZIP_FILE >> ${LOG_FILE}
	echo $DATE_ENTRY If there is some problem, send the zipped file to your software manufacturer. >> ${LOG_FILE}

	zip -j "${ZIP_FILE}" "${LOG_FILE}" "${PY2APP_TXT_FILE}" "${APP_TXT_FILE}" "${APP_DEBUG_LOG}" /private/var/log/install.log
}

# main #

echo $SHELL

getThisScriptDirPath
cd "$DIR_PATH"

if [ "$(id -u)" != "0" ]; then
	echo Running as standard user from command line.
	sudo -s ./preflight
	exit $?
fi

getLogFile

if [[ "$(id -u)" -eq "0" && "$USER" != "root" ]]; then
	echo Running from installer.
	echo $DATE_ENTRY User: $USER >> ${LOG_FILE}
fi

if [[ "$(id -u)" -eq "0" && "$USER" == "root" ]]; then
	echo Running as root from installer.
	echo $DATE_ENTRY User: $USER, Sudo user: $SUDO_USER >> ${LOG_FILE}
fi

isLoggedRootUser
res=$?
if [ $res -eq "1" ]; then
	currentUser=$(ls -l /dev/console | awk '{ print $3 }')
	sudo -u ${currentUser} osascript -e 'tell application "System Events"' -e 'activate' -e 'display dialog "Run the assistant using a normal user account. Do not use root account. Click OK to terminate the assistant." buttons {"OK"} default button 1' -e 'end tell'
	exit 1
fi

set

rm -rf tmp
mkdir tmp
for i in `find . -name "*.pyc"`
do
	echo Removing "$i" >> ${LOG_FILE}
	rm -f "$i"
done

setLogFiles

setDateVar
echo $DATE_ENTRY Assistant started from $DIR_PATH folder. > ${LOG_FILE}

printSystemInformation
checkSystemRequirements

runPy2App
runApp
zipLogs

setDateVar
echo $DATE_ENTRY Assistant finished. >> ${LOG_FILE}

SUCCESS_FILE=$(
echo "$DIR_PATH""/tmp/success")
if [ -f "$SUCCESS_FILE" ]
then
	exit 0
else
	echo $DATE_ENTRY Some problem occurred. >> ${LOG_FILE}
	exit 1		
fi
