#!/usr/bin/env python
from optparse import OptionParser
from os import system
from os.path import exists
from tempfile import NamedTemporaryFile 
from sys import exit

if __name__ == "__main__":
   parser = OptionParser()
   parser.add_option("-d", "--debug", dest="debug", help="Run in debug mode.", 
                     action="store_true", default=False)
   parser.add_option("-c", "--config", dest="displayConfigFilename", metavar="FILENAME",
                     help="PATH to cmsShow GUI configuration", default=None)
   parser.add_option("-g", "--geometry", dest="geometryFilename", metavar="FILENAME",
                     help="PATH to geometry file", default=None)
   parser.add_option("-r", "--root-prompt", dest="rootPrompt", help="show root prompt", action="store_true", default=False)
   opts, args = parser.parse_args()
   
   if not len(args) == 1:
      parser.error("Only one CMSSW configuration file allowed.")
   
   results = {}
   cmsswConfig = args[0]
   if not exists(cmsswConfig):
      parser.error("File not found: %s" % cmsswConfig)

   serviceOpts = ["\"FWFFLooper\""]

   if opts.geometryFilename:
      serviceOpts.append("geometryFilename=cmsShowPrivate.untracked.string(\"%s\")" % opts.geometryFilename)
   if opts.displayConfigFilename:
      serviceOpts.append("displayConfigFilename=cmsShowPrivate.untracked.string(\"%s\")" % opts.displayConfigFilename)
   dest = NamedTemporaryFile(suffix=".py", delete=not opts.debug)
   dest.write(file(cmsswConfig).read())
   dest.write("""
import FWCore.ParameterSet.Config as cmsShowPrivate
process.looper = cmsShowPrivate.Looper(%s)
process.FWFFHelper = cmsShowPrivate.Service("FWFFHelper", rootPrompt = cmsShowPrivate.untracked.bool(%s))
process.add_(cmsShowPrivate.ESProducer("FWRecoGeometryESProducer"))
process.add_(cmsShowPrivate.Service("InitRootHandlers", ResetRootErrHandler = cmsShowPrivate.untracked.bool(False)))
process.maxEvents = cmsShowPrivate.untracked.PSet(
    input = cmsShowPrivate.untracked.int32(-1)
)
""" % (",".join(serviceOpts), opts.rootPrompt))
   dest.flush()
   if opts.debug:
      print "Temporary configuration file can be found at %s" % dest.name
      print "Executing", "cmsRun %s" % dest.name
   system("%scmsRun %s" % (opts.debug and "gdb --args " or "", dest.name))
   dest.close()
