#!/usr/bin/osascript

-- -------------------------------------------------------------------- --
--                                                                      --
--            (C) Kerio Technologies Inc. All rights reserved.          --
--                                                                      --
-- -------------------------------------------------------------------- --

-- Functions.

-- Is application running?
to getRunning(appl)
	if application appl is running then
		return true
	else
		return false
	end if
end getRunning

-- Compare Mac OS X version with supplied "ver" version. 
to minmaxOSVersion(ver, min)
	set decNum to 0
	set numList to characters of (ver as string)
	repeat with num in numList
		set decNum to (16 * decNum) + num
	end repeat
	tell application "Finder" to set sysv to (system attribute "sysv")
	if min then
		if sysv < decNum then return false
	else
		if sysv > decNum then return false
	end if
	return true
end minmaxOSVersion

-- Display dialog
to displayDialog(textMsg)
	do shell script "osascript -e 'tell application \"System Events\"' -e \"activate\" -e \"display dialog \\\"" & textMsg & "\\\" buttons {\\\"OK\\\"} default button 1\" -e 'end tell'"
end displayDialog

-- Logging function
to log {logString, logFile}
	try
		write logString & return to logFile starting at EOF
	on error
	end try	
end log

--
-- Main.
--

-- Start logging
set homeDir to do shell script "printenv HOME"
set kmsLog to homeDir & "/Library/Logs/kerio-ical-config-tool.log"

-- create new log file
set kmsQuotedLog to quoted form of kmsLog 
do shell script "date > " & kmsQuotedLog

set kmsLog to POSIX file kmsLog

try
	set logFile to open for access file kmsLog with write permission
on error
	displayDialog {"Cannot open log file " & kmsLog & "."}
	error
end try
set eof of logFile to 0

tell (current date) to set dateTime to short date string & space & time string & "."
log {"iCal Config Tool setup script started at " & dateTime, logFile}
log {"Mac OS version " & system version of (system info) & ".", logFile}

-- Check version.
if not ((minmaxOSVersion(1050, true)) and (minmaxOSVersion(1070, false))) then
	displayDialog {"iCal Config Tool is designed to run on Mac OS X 10.5 and 10.6 only."}
	log {"Incompatible Mac OS X version.", logFile}
	error
end if

-- Read config file
tell application "Finder"
	set pathToThisFile to path to me
	set scriptFolder to (container of pathToThisFile) as alias as string
	set configFileName to scriptFolder & "KMSInstaller:configure_include.py"
end tell
try
	tell application "Finder"
	set fileContents to paragraphs of (read file configFileName)
	end tell
on error errStr
	set errMsg to "Cannot read configuration.\nError: " & errStr & " \nExiting."
	log {errMsg, logFile}
	tell application "System Events"
		activate
		display dialog errMsg buttons {"OK"} default button 1
	end tell
	error
end try 

repeat with i from 1 to (count of fileContents)
	set theLine to (item i of fileContents)
	if (theLine contains "KMSHTTPPort") and (theLine contains "= 0") then
		displayDialog {"Kerio MailServer has no available HTTP ports. No iCal CalDAV accounts will be created. Contact your administrator about the issue."}
		log {return & "No HTTP ports available.", logFile}
		error
	end if
end repeat

-- Close apps blocking file access.
log {return & "Running applications check started.", logFile}
repeat
	set runningBlockingApps to ""
	set blockingApps to {"iCal", "Directory Utility"}
	repeat with i from 1 to (count of blockingApps)
		set theApp to (item i of blockingApps)
		if getRunning(theApp) then
			set runningBlockingApps to runningBlockingApps & return & "* " & (theApp)
		end if
	end repeat
	
	if runningBlockingApps is equal to "" then
		exit repeat
	else
		displayDialog {"Please close the following application(s) before you continue:" & return & runningBlockingApps & return & return & "Press OK after you have closed the application(s)."}
	end if
end repeat
log {"Running applications check finished.", logFile}

-- Launch Python script.
tell application "Finder"
	set pathToThisFile to path to me
	set scriptFolder to (container of pathToThisFile) as string
	set scriptFolder to POSIX path of scriptFolder
	set scriptFolder to quoted form of scriptFolder
end tell

do shell script "echo " & homeDir & " > " & scriptFolder & "KMSInstaller/homePath"

set scriptResult to "0"

set pyGeneratorResult to ""
log {return & "PyObjC application generator started.", logFile}
try
	set pyGeneratorResult to do shell script "cd " & scriptFolder & "KMSInstaller; sudo python setup.py py2app" with administrator privileges
	log {"PyObjC application generator finished.", logFile}
on error
	log {pyGeneratorResult, logFile}
	log {"PyObjC application generator failed.", logFile}
	set scriptResult to "-1"
end try

if scriptResult contains "0" then
	log {return & "PyObjC application started.", logFile}
	
	try
		close access logFile
		set scriptResult to do shell script "sudo " & scriptFolder & "KMSInstaller/dist/KMSInstaller.app/Contents/MacOS/KMSInstaller" with administrator privileges
		set logFile to open for access file kmsLog with write permission
		log {"PyObjC application finished.", logFile}
		
	on error
		set logFile to open for access file kmsLog with write permission
		set scriptResult to "-1"
		log {scriptResult, logFile}
		log {"PyObjC application failed.", logFile}
		
	end try
	
end if

if scriptResult contains "-1" then
	log {return & "Finishing with error (" & scriptResult & ").", logFile}
end if

tell (current date) to set dateTime to short date string & space & time string & "."
log {return & "iCal Config Tool setup script finished at " & dateTime, logFile}
close access logFile

if scriptResult contains "-1" then
	error
end if

return scriptResult
