#!/usr/bin/python

import sys
import os.path
import shlex
from subprocess import Popen, PIPE

debug = []
#debug = ['-Xdebug', '-Xrunjdwp:transport=dt_shmem,server=y,address=jas3,suspend=n']

scriptFullPath = os.path.abspath(sys.argv[0])
#print "Script path: ", scriptFullPath

binDir = os.path.dirname(scriptFullPath)
#print "Bin dir: ", binDir

distDir = os.path.dirname(binDir)
#print "Distribution dir: ", distDir

CCS_JAVA_OPTS = os.getenv("CCS_JAVA_OPTS", "")
#print "CCS_JAVA_OPTS = ", CCS_JAVA_OPTS

os.putenv("CCS_DISTRIBUTION_HOME", distDir)
#print "CCS_DISTRIBUTION_HOME = ", os.getenv("CCS_DISTRIBUTION_HOME")

#FIXME
os.putenv("CCS_RESOURCE_PATH", distDir)

mainJar = os.path.join(distDir, "share", "java", "org-lsst-ccs-bootstrap-3.0.11.jar")
#print "Main jar = ", mainJar

LD_LIBRARY_PATH = Popen(['java', '-cp', mainJar, 'org.lsst.ccs.bootstrap.BootstrapEnvironmentUtils', 'LD_LIBRARY_PATH'], stdout=PIPE).communicate()[0].strip()
os.putenv("LD_LIBRARY_PATH", LD_LIBRARY_PATH)
#print "LD_LIBRARY_PATH = ", LD_LIBRARY_PATH

BOOTSTRAP_JAVA_OPTS = Popen(['java', '-cp', mainJar, 'org.lsst.ccs.bootstrap.BootstrapEnvironmentUtils', 'JAVA_OPTS'] + sys.argv[1:] , stdout=PIPE).communicate()[0].strip()
#print "BOOTSTRAP_JAVA_OPTS = ", BOOTSTRAP_JAVA_OPTS

CLASSPATH = Popen(['java', '-cp', mainJar, 'org.lsst.ccs.bootstrap.BootstrapEnvironmentUtils', 'CLASSPATH'] + sys.argv[1:], stdout=PIPE).communicate()[0].strip()
#print "CLASSPATH = ", CLASSPATH

out = 'java ' + CCS_JAVA_OPTS +" "+ BOOTSTRAP_JAVA_OPTS + ' -cp ' + CLASSPATH + ' org.lsst.ccs.bootstrap.Bootstrap ' + sys.argv[1]
print Popen(['java'] + debug + shlex.split(CCS_JAVA_OPTS) + shlex.split(BOOTSTRAP_JAVA_OPTS) + ['-cp', CLASSPATH, 'org.lsst.ccs.bootstrap.Bootstrap'] + sys.argv[1:], stdout=PIPE).communicate()[0]

