#!/usr/bin/env python
import sys,os,getopt
from Carbon.Launch import LSFindApplicationForInfo
from Carbon.CoreFoundation import kCFURLPOSIXPathStyle
#===============================================================================================
execute = 1
#===============================================================================================
def Usage():
	print ("Usage: " + sys.argv[0] + " [-n] check-Kind [checkURL]")
	print ("")
	print ("check-Kind: email,static,normal,verbose")
	print ("")
	print (" auto-update is enabled when using email,normal or verbose")
	sys.exit(2)
#===============================================================================================
def	RunCmd(DoCmd):
	if not execute: 
		print(DoCmd)
		return ""
	doit = os.popen(DoCmd) 
	feedback = doit.read()
	doit.close()
	return feedback.rstrip()
#===============================================================================================
def	FindApp(AppIdentifier):
	kLSUnknownCreator = '\x00\x00\x00\x00'
	try:
		(fsRef, cfURL) = LSFindApplicationForInfo(kLSUnknownCreator, AppIdentifier, None)
		return fsRef.as_pathname()
	except:
		print ("Application " + AppIdentifier + " not found")
	return ""
#===============================================================================================
try:
	opts, args = getopt.getopt(sys.argv[1:], "n")
except getopt.GetoptError:
	Usage()
for o, a in opts:
	if o == "-n":
		execute = 0
#===============================================================================================
#
if len(args) < 1: Usage()
#
checkURL = ""
checkVariante = ""
checkApp = FindApp("ch.ruedi.osaapp.CheckInstallations")
#
checkVariante = args[0].lower()
exeFile = checkApp + "/Contents/Resources/checkVersions.py"
if os.path.isfile(exeFile):
	if len(args) > 1: checkURL = args[1]
	#		
	#	zuerst versuchen wir uns aufzudatieren...:
	#		
	if "static" not in checkVariante:
		requiredCmdFilepath = "/Applications/CheckInstallations.app/Contents/Resources/checkVersions.py"
		if os.path.isfile(requiredCmdFilepath):
			checkCmd = "python " + exeFile + " --filter checkVersions --load -v https://www.wsl.ch/land/inventory/iceberg/versions/basicClient.rcvk"
			RunCmd(checkCmd)
		else:
			print ("auto-update requires installation at "+requiredCmdFilepath+",\nnot in "+exeFile)
	#		
	#		
	#		
	if "email" in checkVariante:
		checkCmd = exeFile + " -e " + checkURL
	elif "verbose" in checkVariante:
		checkCmd = exeFile + " -v " + checkURL
	elif "normal" in checkVariante:
		checkCmd = exeFile + " " + checkURL
	else:
		Usage()
	print RunCmd(checkCmd)
else:
	print (exeFile+" not found")
	