import os,sys,getopt, subprocess

telescopePath = "$KEPLERROOT/eos/lhcb/testbeam/ut/TelescopeData/July2015/RootFiles"

inputPathPedestal = "$KEPLERROOT/eos/lhcb/testbeam/ut/OfficialData/July2015/BoardA6/RawData/"
inputPathSignal = "$KEPLERROOT/eos/lhcb/testbeam/ut/OfficialData/July2015/BoardA6/RawData/"

pedFile = "Pedestal-B6-A-209-0.dat"
sigFile = "Run_Bias_Scan-B6-A-299-8431.dat"
if __name__=="__main__":
        try:
                opts,args = getopt.getopt(sys.argv[1:],"fp:fs:",["pedestal","signal"])
        except getopt.GetoptError as err:
                print str(err)
                usage()
                sys.exit(2)
        for o, a in opts:
                if o in ('-fp','--pedestal'):
                        pedFile = str(a)
                if o in ('-fs','--signal'):
                        sigFile = str(a)


inputFilePedestal = inputPathPedestal+pedFile
inputFileSignal = inputPathSignal+sigFile
print inputFilePedestal
print inputFileSignal
subprocess.call('source /afs/cern.ch/project/eos/installation/lhcb/etc/setup.sh',shell=True)
subprocess.call('/afs/cern.ch/project/eos/installation/0.3.15/bin/eos.select -b fuse mount $KEPLERROOT/eos',shell=True)
shFile = open(os.environ["KEPLERROOT"]+"/../run_k.sh","w")
shFile.write('#!/bin/bash\n')
shFile.write('cd $KEPLERROOT/../TbUT\n')
shFile.write('python options/TbUTPedestal_conf.py -f '+inputFilePedestal+"\n")
shFile.write('python options/TbUTRun_conf.py -f '+inputFileSignal+"\n")
shFile.write('cd ../../\n')
shFile.write('mkdir -p output\n')
shFile.write('cd output\n')
shFile.write('gaudirun.py $KEPLERROOT/../TbUT/options/TbUTPedestal.py\n')
shFile.write('gaudirun.py $KEPLERROOT/../TbUT/options/TbUTRun.py\n')
shFile.write('gaudirun.py $KEPLERROOT/../TbUT/options/TbUTRun.py\n')
shFile.write('. LbLogin.sh -c x86_64-slc6-gcc48-opt\n')
shFile.write('. SetupProject.sh LHCb v36r2\n')
shFile.write('cd ../Tb/TbUT/scripts/AddTrigTracks\n')
shFile.write('make\n')
shFile.write('cd ../../../../output\n')
shFile.write('pwd\n')
shFile.write('./../Tb/TbUT/scripts/AddTrigTracks/combDUTwithTrack -i '+sigFile[:-4]+'_Tuple.root -t '+telescopePath+'/Run'+sigFile[-8:-4]+'/Output/Kepler-tuple.root -n '+sigFile[:-4]+'.root -o outputFile_'+sigFile[-8:-4]+'.root\n')
os.environ['OUTPUTFILE'] = sigFile[-8:-4]
subprocess.call("sed -i 's/defRUN/"+sigFile[-8:-4]+"/g' $KEPLERROOT/../TbUT/scripts/AnalysisBase_Inputs.h",shell=True)
shFile.write('\nmkdir -p Plots')
shFile.write('\nroot -b -q ../Tb/TbUT/scripts/runClusterWithTrackAna.C')
shFile.write('\n. LbLogin.sh -c x86_64-slc6-gcc49-opt\n')
shFile.write('. SetupProject.sh LHCb\n')
shFile.close()
subprocess.call("chmod +x "+os.environ["KEPLERROOT"]+"/../run_k.sh",shell=True)
os.system('/$KEPLERROOT/../run_k.sh')
subprocess.call("sed -i 's/"+sigFile[-8:-4]+"/defRUN/g' $KEPLERROOT/../TbUT/scripts/AnalysisBase_Inputs.h",shell=True)
