#! /usr/bin/env python
#-*- python -*-

"""Defines 'smart' convenience wrapper for invoking CRDS tools that
hides internal package structure.
"""
import sys
import shlex
import subprocess

from crds.pysh import usage

if len(sys.argv) > 2 and "--help" in sys.argv:
    del sys.argv[sys.argv.index("--help")]
    RESTORE_HELP = True
elif len(sys.argv) == 2 and "--help" not in sys.argv:
    RESTORE_HELP = True
else:
    RESTORE_HELP = False

usage("<command> <parameters...>", 1, help="""

'crds' is a wrapper used to invoke various CRDS sub-programs.

For example,  to assign HST best reference files,  do:

    $ crds bestrefs --files *.fits  --update-bestrefs

Available commands:

list                -- print information about CRDS configuration, etc. 
certify             -- check CRDS reference and rules files
bestrefs            -- assign bestrefs to datasets, regressions, repro
sync                -- manage local CRDS cache, download rules + references
diff                -- difference CRDS rules and references
rowdiff             -- difference reference tables
matches             -- list matching criteria relative to particular rules
checksum            -- update rmap checksum
query_affected      -- download CRDS new reference files affected dataset IDs
uniqname            -- rename HST files with new CDBS-style names
get_synphot         -- download synphot references
submit              -- simple command line file submission
rc_submit           -- extended command line file submisson

For more detail about individual commands use --help:

e.g. crds list --help

""")

if RESTORE_HELP:
    sys.argv.append("--help")

REMAPPED_MODULES = {
    "query_affected"  : "crds.misc.query_affected",
    "sql" : "crds.misc.sql",
    "check_archive" : "crds.misc.check_archive",
    "datalvl": "crds.misc.datalvl",
    "uniqname":  "crds.misc.uniqname",

    "refactor" : "crds.refactoring.refactor",
    "refactor2" : "crds.refactoring.refactor2",
    "newcontext" : "crds.refactoring.newcontext",
    "checksum" : "crds.refactoring.checksum",
    "get_synphot" : "crds.misc.get_synphot",
    "submit" : "crds.submit",
    "rc_submit" : "crds.submit.rc_submit",
}

remapped = REMAPPED_MODULES.get(sys.argv[1], "crds." + sys.argv[1])

def quote_strings(args):
    """Re-quote the command line parameters to prevent losing required quoting
    when the modified command line is reissued.
    """
    return [shlex.quote(arg) for arg in args]

if "--debug-traps" in sys.argv or "--pdb" in sys.argv:
    command = [sys.executable, "-i", "-m", remapped] + sys.argv[2:]
else:
    command = [sys.executable, "-m", remapped] + sys.argv[2:]

# print("command:", command)

status = subprocess.call(command, stdin=sys.stdin)
sys.exit(status)


