global appSig
global casaBinDir
global casaRoot
global thisVersion

global casapy
global casaviewer
global casabrowser
global buildmytasks
global casaplotms


global defaultCasapyLinkLocation
global defaultCasaViewerLinkLocation
global defaultCasaBrowserLinkLocation
global defaultCasaPlotMSLinkLocation
global defaultBuildTasksLinkLocation


set defaultCasapyLinkLocation to "/usr/bin/casapy"
set defaultCasaViewerLinkLocation to "/usr/bin/casaviewer"
set defaultCasaBrowserLinkLocation to "/usr/bin/casabrowser"
set defaultCasaPlotMSLinkLocation to "/usr/bin/casaplotms"
set defaultBuildTasksLinkLocation to "/usr/bin/buildmytasks"

set casaRoot to POSIX path of (path to me) & "Contents"
set casaBinDir to casaRoot & "/MacOS"

set casapy to casaBinDir & "/casapy"
set casaviewer to casaBinDir & "/casaviewer"
set casabrowser to casaBinDir & "/casabrowser"
set casaplotms to casaBinDir & "/casaplotms"
set buildmytasks to casaBinDir & "/buildmytasks"

set appSig to ""
try
	set appSig to ¬
		do shell script "defaults read" & space & (quoted form of (casaRoot & "/Info") & space & "CFBundleIdentifier")
on error
	display dialog "defaults read" & space & (quoted form of (casaRoot & "/Info") & space & "CFBundleIdentifier")
end try

set thisVersion to ""
try
	set thisVersion to ¬
		do shell script "cat" & space & (quoted form of (casaRoot & "/Resources/VERSION"))
	set thisVersion to the first word of thisVersion
on error
	display dialog "cat" & space & (quoted form of (casaRoot & "/Resources/VERSION"))
end try

set casaSetupMode to readAppPref("casa.setup.mode")
if (length of casaSetupMode) is 0 then
	set casaSetupMode to "dontAsk"
	writeAppPref("casa.setup.mode", "askUser") -- ask next time
end if
try
	if (the clipboard as text) starts with "CASA setup" then set casaSetupMode to "askUser"
on error errorStr number errorNumber
	-- this fails if the clipboard is empty. ye cats!
	-- display dialog "examine clipboard: " & errorStr & space & errorNumber
end try


if casaSetupMode is not "noverify" then
	verifySetup(casaSetupMode is "askUser")
end if


tell application "Terminal"
	activate
	do script casapy
end tell

-------------------------------------------------

on verifySetup(interactive)
	set changeCasaVersion to verifyVersion(interactive)
	
	verifySymlink(casapy, defaultCasapyLinkLocation, interactive, changeCasaVersion)
	verifySymlink(casaviewer, defaultCasaViewerLinkLocation, interactive, changeCasaVersion)
	verifySymlink(casabrowser, defaultCasaBrowserLinkLocation, interactive, changeCasaVersion)
	verifySymlink(casaplotms, defaultCasaPlotMSLinkLocation, interactive, changeCasaVersion)
	verifySymlink(buildmytasks, defaultBuildTasksLinkLocation, interactive, changeCasaVersion)
	
	-- verifyDataDir(interactive, changeCasaVersion)
	set dataRepos to (casaRoot & "/Resources/casa-data")
	writeAppPref("casa.data.path", dataRepos)
end verifySetup


on readAppPref(selector)
	set information to ""
	try
		set information to (do shell script ("defaults read" & space & appSig & space & selector))
	on error -- no such file, etc
		-- eat all errors
	end try
	return information
end readAppPref


on writeAppPref(selector, val)
	try
		do shell script ("defaults write" & space & appSig & space & selector & space & val)
	end try
end writeAppPref





on verifyDataDir(interactive, newVersion)
	set createRepository to false
	set symLinkLocation to (casaRoot & "/data")
	set starterData to (casaRoot & "/Resources/casa-data")
	
	set symLinkTarget to "/opt/casa/data"
	set savedLinkTarget to readAppPref("casa.data.path")
	if length of savedLinkTarget > 0 then set symLinkTarget to savedLinkTarget
	
	-- set dlgMessage to "Where is your CASA data repository?"
	--
	-- if newVersion and interactive then set symLinkTarget to ¬
	-- 	the text returned of (display dialog dlgMessage with title ¬
	-- 		"CASA shell environment setup" default answer ¬
	-- 		symLinkTarget buttons {"Link to CASA repository"} ¬
	-- 		default button 1)
	
	
	set pathItems to fixPaths(symLinkTarget)
	set docpath to first item of pathItems
	set docDir to second item of pathItems
	
	try
		set fileInfo to info for (file docpath)
		if not (folder of fileInfo or ¬
			file type of fileInfo is "slnk") then
			-- give up, a file is in the way
			set updateLink to false
			if interactive then ¬
				display dialog symLinkTarget & return & ¬
					" Is a file, not a data repository." & ¬
					" Move it out of the way and re-run CASA." with icon 1 ¬
					buttons {"Cancel"}
		end if
	on error errorStr number errorNumber
		-- return if user clicked Cancel (-128)
		if errorNumber is -128 then
			return
		else if errorNumber is -43 or errorNumber is -120 then
			-- file not found; the data repository needs to be created
			set createRepository to true
		else
			display dialog "create casa data repository A: " & errorStr & space & errorNumber
		end if
	end try
	-- --
	-- -- update the symlink, if necessary
	-- try
	-- 	set shellCmd to "stat -f %Y" & space & (quoted form of symLinkLocation)
	-- 	set oldLinkTarget to (do shell script shellCmd)
	-- 	if oldLinkTarget ≠ symLinkTarget then
	-- 		set needAdminPermission to checkFolderPermissions(casaRoot)
	-- 		do shell script "cd" & space & (quoted form of casaRoot) & space & ¬
	-- 			"&& mkdir -p" & space & (quoted form of docDir) & space & ¬
	-- 			"&& ln -s -f" & space & (quoted form of symLinkTarget) & space & ¬
	-- 			"data" administrator privileges needAdminPermission
	-- 	end if
	-- on error errorStr number errorNumber
	-- 	display dialog "update casa data repository symlink: " & errorStr & space & errorNumber
	-- end try
	--
	-- create the data repository, if necessary
	--
	if createRepository then
		try
			set needAdminPermission to checkFolderPermissions(docDir)
			do shell script ¬
				"ditto" & space & (quoted form of starterData) & space ¬
				& (quoted form of symLinkTarget) ¬
				administrator privileges needAdminPermission
		on error errorStr number errorNumber
			display dialog "create casa data repository: " & errorStr & space & errorNumber
		end try
	end if
	writeAppPref("casa.data.path", symLinkTarget)
end verifyDataDir



on verifyVersion(interactive)
	set updateCasa to false
	set savedVersion to readAppPref("casa.version")
	
	try
		if (length of savedVersion) = 0 then
			set updateCasa to true
			if interactive then
				set answer to the button returned of ¬
					(display dialog "This appears to be the first time you've run CASA " & thisVersion ¬
						buttons {"Set up shell environment", "Ask me later", ¬
						"No changes and don't ask again."} ¬
						default button 2 ¬
						giving up after 20)
				if answer is "Ask me later" then
					set updateCasa to false
				else if answer is "No changes and don't ask again." then
					set updateCasa to false
					writeAppPref("setup", "noverify")
				end if
			end if
		else -- savedVersion is set
			if thisVersion is not savedVersion then
				set updateCasa to true
				if interactive then
					set answer to the button returned of ¬
						(display dialog "This version of CASA is different from the one you had previously installed." & ¬
							" Do you want to set this new version " & thisVersion & ¬
							" as the default CASA?" buttons {"Previous version " & savedVersion, "This version " & thisVersion} ¬
							default button 2)
					if answer begins with "Previous" then
						set updateCasa to false
					end if
				end if
			end if
		end if
	on error errorStr number errorNumber
		if errorNumber is -128 then
			-- user hit "Cancel" in a dialog box
			set updateCasa to false
		else
			display dialog errorStr & space & errorNumber
			error errorNumber
		end if
	end try
	-------
	if updateCasa then writeAppPref("casa.version", thisVersion)
	return updateCasa
end verifyVersion



on verifySymlink(linkTarget, linkLocation, interactive, newVersion)
	set updateLink to true
	set symLinkTarget to linkTarget
	set symLinkLocation to linkLocation
	set dlgMessage to "Please select a location for the casapy symlink. It should be a directory that is in your PATH."
	set savedLinkLocation to readAppPref("casa.symlink.location")
	if length of savedLinkLocation > 0 then set symLinkLocation to savedLinkLocation
	
	if newVersion and interactive then set symLinkLocation to ¬
		the text returned of (display dialog dlgMessage with title ¬
			"CASA shell environment setup" default answer ¬
			symLinkLocation buttons {"Create Symlink"} ¬
			default button 1)
	
	
	set pathItems to fixPaths(symLinkLocation)
	set docpath to first item of pathItems
	set docDir to second item of pathItems
	
	try
		set fileInfo to info for (file docpath)
		if folder of fileInfo then
			set docDir to symLinkLocation
			set symLinkLocation to symLinkLocation & "/casapy"
			set docpath to docpath & ":casapy"
			set fileInfo to info for (file docpath)
		end if
		
		if file type of fileInfo is "slnk" then
			set shellCmd to "stat -f %Y" & space & (quoted form of symLinkLocation)
			set oldLinkTarget to (do shell script shellCmd)
			if oldLinkTarget is symLinkTarget then set updateLink to false
		else
			-- give up, a file is in the way
			set updateLink to false
			if interactive then ¬
				display dialog symLinkLocation & return & ¬
					" already exists and is not a symlink." & ¬
					" Move it out of the way to point to this version of CASA." with icon 1 ¬
					buttons {"Cancel"}
		end if
	on error errorStr number errorNumber
		-- ignore  file not found (-43), return if user clicked Cancel (-128)
		if errorNumber is -128 then
			return
		else if errorNumber is not -43 then
			error errorNumber
		end if
	end try
	--
	-- re-create the symbolic link, if necessary
	if updateLink then
		try
			set needAdminPermission to checkFolderPermissions(docDir)
			do shell script ¬
				"ln -s -f" & space & (quoted form of symLinkTarget) & space & (quoted form of symLinkLocation) ¬
				administrator privileges needAdminPermission
		on error errorStr number errorNumber
			display dialog errorStr & space & errorNumber
		end try
	end if
end verifySymlink


on checkFolderPermissions(posixPath)
	set answer to ""
	set needAdminPermission to true
	--
	try
		set infoStr to (do shell script "ls -ld " & (quoted form of posixPath))
		
		set filePerms to (characters 1 through 13 of infoStr)
		
		set info to words of ((characters 14 through (the length of infoStr) of infoStr) as string)
		
		set fileOwner to second item of info
		set fileGroup to third item of info
		
		set myUserName to system attribute "USER"
		set myGroups to (do shell script "groups")
		
		
		set ownerPerm to items 2 through 4 of filePerms
		set groupPerm to items 5 through 7 of filePerms
		set worldPerm to items 8 through 10 of filePerms
		
		if "w" is in worldPerm then
			set answer to "everyone can write to this"
			set needAdminPermission to false
		else
			if myUserName is fileOwner then
				set answer to "you own this"
				set needAdminPermission to false
			else
				if fileGroup is in myGroups then
					set answer to "you are in the group"
					if "w" is in groupPerm then
						set answer to answer & " and it's group writable"
						set needAdminPermission to false
					else
						set answer to answer & " but not group writable"
					end if
				else
					set answer to "you're not it the " & fileGroup & " group"
				end if
				set answer to answer & " and symLinkLocationou're not " & fileOwner & "."
			end if
			
		end if
	on error errorStr number errorNumber
		display dialog errorStr & space & errorNumber
	end try
	return needAdminPermission
end checkFolderPermissions



on fixPaths(posixPath)
	-- this is really stupid, but AppleScript coercion of
	-- POSIX paths such as "/usr/bin" to 
	-- legacy AppleScript paths such as ":volume:usr:bin"
	-- will silently resolve a symlink to its target in
	-- the POSIX path
	-- so "/usr/bin/casapy" as an Applescript path would
	-- be ":volname:Applications:CASA.app:Contents:MacOS:casapy"
	--
	-- and there would be no way to talk about the symlink itself.
	-- This led to insane bugs in the symlink-setup code.
	-- 
	-- So in this routine, we convert the paths with string manipulation
	-- 
	-- darn kids
	--	
	set search_string to "/"
	set replacement_string to ":"
	set oldDelims to AppleScript's text item delimiters
	set AppleScript's text item delimiters to the search_string
	set docpath to text items of posixPath
	set docDir to (text items 1 through ((length of docpath) - 1) of docpath) as text
	set AppleScript's text item delimiters to the replacement_string
	set docpath to text items of docpath as text
	set rootVolName to first item of (text items of (path to system folder as string))
	set AppleScript's text item delimiters to the oldDelims
	
	set docpath to rootVolName & docpath
	
	return {docpath, docDir}
end fixPaths


