#!/usr/bin/env python3
import sys
import os
import argparse

from HLTrigger.Configuration.extend_argparse import *
import HLTrigger.Configuration.Tools.confdb as confdb
import HLTrigger.Configuration.Tools.options as options

# define an argparse parser to parse our options
textwidth = int( 80 )
try:
    textwidth = int( os.popen("stty size 2> /dev/null", "r").read().split()[1] )
except:
    pass
formatter = FixedWidthFormatter( HelpFormatterRespectNewlines, width = textwidth )

parser = argparse.ArgumentParser(
  description       = 'Extract an HLT configuration (or fragment thereof) from the ConfDB database.''',
  argument_default  = argparse.SUPPRESS,
  formatter_class   = formatter,
  add_help          = False )

# read defaults
defaults = options.HLTProcessOptions()

# required argument
parser.add_argument('menu',
                    action  = 'store',
                    type    = options.ConnectionHLTMenu,
                    metavar = 'MENU',
		    help    = 'HLT menu to dump from the database. Supported formats are:\n  - /path/to/configuration[/Vn]\n  - [[{v1|v2|v3}/]{run3|run2|online|adg}:]/path/to/configuration[/Vn]\n  - run:runnumber\nThe possible converters are "v1", "v2, and "v3" (default).\nThe possible databases are "run3" (default, used for offline development), "run2" (used for accessing run2 offline development menus), "online" (used to extract online menus within Point 5) and "adg" (used to extract the online menus outside Point 5).\nIf no menu version is specified, the latest one is automatically used.\nIf "run:" is used instead, the HLT menu used for the given run number is looked up and used.\nNote other converters and databases exist as options but they are only for expert/special use.' )

# options
parser.add_argument('--process',
                    dest    = 'name',
                    action  = 'store',
                    default = defaults.name,
                    metavar = 'PROCESS',
                    help    = 'Override the process name (the default is %(default)s)' )
parser.add_argument('--type',
                    dest    = 'type',
                    action  = 'store',
                    metavar = 'TYPE',
                    choices = options.globalTag,
                    default = defaults.type,
                    help    = 'Set global options according to a specific HLT luminosity and type (%(choices)s).' )
parser.add_argument('--globaltag',
                    dest    = 'globaltag',
                    action  = 'store',
                    metavar = 'TAG',
                    default = defaults.globaltag,
                    help    = 'Override the GlobalTag in the HLT menu:\n- when running on data, the default behaviour is to not override the GobalTag in the HLT menu\n- when running on MC, the default behaviour is to use the GlobalTag from "type" and the current PyRelVal configuration.\nTo run on data with a different release than the menu was designed for, try "auto:hltonline"' )
parser.add_argument('--l1',
                    dest    = 'l1',
                    action  = 'store',
                    type    = options.ConnectionL1TMenu,
                    default = defaults.l1,
                    metavar = 'MENU',
                    help    = 'Override the L1 menu, using the given payload from the database. %(metavar)s should have the format "L1GtTriggerMenu_MENU_mc".\nThe default behaviour is to run with the L1 menu from the GlobalTag' )
parser.add_argument('--l1Xml',
                    dest    = 'l1Xml',
                    action  = 'store',
                    type    = options.ConnectionL1TMenuXml,
                    default = defaults.l1Xml,
                    metavar = 'MENU',
                    help    = 'Override the L1 menu, using the given Xml file. %(metavar)s should have the format "L1Menu_Collisions2012_v0_L1T_Scales_20101224_Imp0_0x1027.xml".\nThe default behaviour is to run with the L1 menu from the GlobalTag' )
parser.add_argument('--l1-emulator',
                    dest    = 'emulator',
                    action  = 'store',
                    metavar = 'EMULATOR',
                    nargs   = '?',
                    choices = [ 'Full', 'FullMC', 'Full2015Data', 'uGT' ],
                    default = defaults.emulator,
                    const   = 'Full',
                    help    = 'Run the Full stage-2 L1T emulator.' )

group = parser.add_mutually_exclusive_group()
group.add_argument('--dbproxy',
                    dest    = 'proxy',
                    action  = 'store_true',
                    default = defaults.proxy,
                    help    = 'Use a socks proxy to connect outside CERN network (default: False)' )
group.add_argument('--dbtunnel',
                    dest    = 'tunnel',
                    action  = 'store_true',
                    default = defaults.tunnel,
                    help    = 'Use direct tunnel to connect outside CERN network (default: False)' )

parser.add_argument('--dbproxyport',
                    dest    = 'proxy_port',
                    action  = 'store',
                    metavar = 'PROXYPORT',
                    default = defaults.proxy_port,
                    help    = 'Port of the socks proxy (default: 8080)' )
parser.add_argument('--dbproxyhost',
                    dest    = 'proxy_host',
                    action  = 'store',
                    metavar = 'PROXYHOST',
                    default = defaults.proxy_host,
                    help    = 'Host of the socks proxy (default: "localhost")' )
parser.add_argument('--dbtunnelport',
                    dest    = 'tunnel_port',
                    action  = 'store',
                    metavar = 'TUNNELPORT',
                    default = defaults.tunnel_port,
                    help    = 'Port when using a direct tunnel on localhost (default: 10121)' )

group = parser.add_mutually_exclusive_group()
group.add_argument('--prescale',
                    dest    = 'prescale',
                    action  = 'store',
                    default = defaults.prescale,
                    help    = 'Force using one specific prescale column.\nUse "--prescale none" to run without any HLT prescales' )
group.add_argument('--no-prescale',
                    dest    = 'prescale',
                    action  = 'store_const',
                    const   = 'none',
                    help    = 'Same as "--prescale none"' )
group.add_argument('--unprescale',
                    dest    = 'prescale',
                    action  = 'store_const',
                    const   = 'none',
                    help    = 'Same as "--prescale none"' )

parser.add_argument('--open',
                    dest    = 'open',
                    action  = 'store_true',
                    default = defaults.open,
                    help    = 'Run the HLT in "open" mode, overriding all ED/HLTFilters to always pass (overrides "--prescale" and implies "--prescale none")' )
parser.add_argument('--eras',
                    dest    = 'eras',
                    action  = 'store',
                    type    = str,
                    default = defaults.eras,
                    metavar = 'ERAS',
                    help    = 'Select the defined Eras in HLT configuration (e.g. phase1Pixel)' )
parser.add_argument('--customise',
                    dest    = 'customise',
                    action  = 'store',
                    type    = str,
                    default = defaults.customise,
                    metavar = 'CUSTOMISE',
                    help    = 'Apply the user-defined customization functions using the format HLTrigger/Configuration/customizeHLTTrackingForPhaseI2017.customizeHLTForPFTrackingPhaseI2017' )
parser.add_argument('--error-events',
                    dest    = 'errortype',
                    action  = 'store_true',
                    default = defaults.errortype,
                    help    = 'Modify all HLTTriggerTypeFilter EDFilters to accept only error events (SelectedTriggerType = 0)' )
parser.add_argument('--profiling',
                    dest    = 'profiling',
                    action  = 'store_true',
                    default = defaults.profiling,
                    help    = 'Instrument the menu with the modules for profiling studies (hltGetRaw and hltGetConditions), disable options' )
parser.add_argument('--timing',
                    dest    = 'timing',
                    action  = 'store_true',
                    default = defaults.timing,
                    help    = 'Instrument the menu with the Service, EDModules and EndPath needed for timing studies (implies --profiling)' )
parser.add_argument('--paths',
                    dest    = 'paths',
                    action  = 'store',
                    type    = str,
                    default = defaults.paths,
                    metavar = 'PATHS',
                    help    = 'Include only the given comma-separated-list of paths in the dump (wildcards are accepted)\nNote that in a full dump the "smart prescale" modules will likely fail, unless removed with "--output none" or "--output minimal"' )
parser.add_argument('--input',
                    dest    = 'input',
                    action  = 'store',
                    type    = str,
                    default = defaults.input,
                    metavar = 'SOURCE',
                    help    = 'If set, specify the SOURCE input file(s) or dataset, otherwise a default is chosen up depending on the other options.\nSOURCE can be a single file nane, a comma-separated list of file names, or have the format "dataset:DATASET" to query a DATASET definition from DAS' )
parser.add_argument('--parent',
                    dest    = 'parent',
                    action  = 'store',
                    type    = str,
                    default = defaults.parent,
                    metavar = 'PARENT',
                    help    = 'If set, specify the PARENT input file(s) or dataset, using the same syntax as SOURCE, above' )
parser.add_argument('--max-events',
                    dest    = 'events',
                    action  = 'store',
                    type    = int,
                    default = defaults.events,
                    metavar = 'EVENTS',
                    help    = 'Run on EVENTS events (-1 for unlimited)' )
parser.add_argument('--setup',
                    dest    = 'setup',
                    action  = 'store',
                    type    = str,
                    default = defaults.setup,
                    metavar = 'STORE',
                    help    = 'If set, download setup_cff from the specified configuration and load it. Note, it is forced to be the same database and converter as specified by primary menu configuration, in fact it is an error to specify a converter/database here and the command will fail' )

group = parser.add_mutually_exclusive_group()
group.add_argument('--output',
                    dest    = 'output',
                    action  = 'store',
                    metavar = 'OUTPUT',
                    choices = [ 'all', 'minimal', 'none', 'full' ],
                    default = defaults.output,
                    help    = 'Use:\n- "all" to output all output modules (default)\n- "minimal" to only output the TriggerResults\n- "none" to remove all output modules\n- "full" to output a single root file with "keep *" event content.' )
group.add_argument('--no-output',
                    dest    = 'output',
                    action  = 'store_const',
                    const   = 'none',
                    help    = 'Same as "--output none"' )

group = parser.add_mutually_exclusive_group()
group.add_argument('--data',
                    dest    = 'data',
                    action  = 'store_true',
                    default = defaults.data,
                    help    = 'Prepare a menu for running on data (raw events in "source") (default)' )
group.add_argument('--mc',
                    dest    = 'data',
                    action  = 'store_false',
                    default = not defaults.data,
                    help    = 'Prepare a menu for running on MC (raw events in "rawDataCollector")' )

parser.add_argument('--hilton',
                    dest    = 'hilton',
                    action  = 'store_true',
                    default = defaults.hilton,
                    help    = 'Keep the hilton-specific modules' )

group = parser.add_mutually_exclusive_group()
group.add_argument('--full',
                    dest    = 'fragment',
                    action  = 'store_false',
                    default = not defaults.fragment,
                    help    = 'Generate a full configuration file, with minimal modifications (default)' )
group.add_argument('--fragment', '--cff',
                    dest    = 'fragment',
                    action  = 'store_true',
                    default = defaults.fragment,
                    help    = 'Generate a stripped down configuration file fragment, for inclusion by e.g. cmsDriver.py (with no input or output sections)' )

group = parser.add_mutually_exclusive_group()
group.add_argument('--online',
                    dest    = 'unused',
                    action  = 'store_true',
                    help    = 'Ignored' )
group.add_argument('--offline',
                    dest    = 'unused',
                    action  = 'store_true',
                    help    = 'Ignored' )

# redefine "--help" to be the last option, and use a customized message
parser.add_argument('--help',
                    action  = 'help',
                    help    = 'Show this help message and exit' )

# parse command line arguments and options
config = parser.parse_args(namespace = options.HLTProcessOptions())

# do not include db-proxy/tunnel options in 1st-line comment
cmdArgs, skipNext = [], False
for cmdArg in sys.argv:
  if skipNext:
    skipNext = False
    continue
  if cmdArg.startswith('--dbproxy') or cmdArg.startswith('--dbtunnel'):
    if cmdArg.startswith('--dbproxyh') or cmdArg.startswith('--dbproxyp') or cmdArg.startswith('--dbtunnelp'):
      skipNext = '=' not in cmdArg
    continue
  cmdArgs += [cmdArg]
cmdArgs[0] = os.path.basename(cmdArgs[0])

cmdLine = ' '.join(cmdArgs)
print('# ' + cmdLine)
print()
print(confdb.HLTProcess(config).dump())
