import sys, commands, string, os

# path to inside of Sage.app
appname = string.join(string.split(sys.argv[0], '/')[:-3], '/')
sageDir = appname + '/Contents/Resources/sage'
sageScriptOrig = sageDir + '/sage'
sageScriptNew = sageDir + '/sageMac.command'

# copy Sage startup script to end in .command so that OS X will launch it 
commands.getoutput('cp -f %s %s' % (sageScriptOrig, sageScriptNew))

# edit sageScriptNew to reflect current location (sageDir)
f = open(sageScriptNew)
lines = f.read()
f.close()

splitLines = string.split(lines, '"')
newLines = [splitLines[0], sageDir]
newLines.extend(splitLines[2:])
newLines = string.join(newLines, '"')

f = open(sageScriptNew, 'w')
f.write(newLines)
f.close()

# run the script
os.execl('/usr/bin/open', '/usr/bin/open', sageScriptNew)
