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

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

from __future__ import print_function

import sys
import shlex
import subprocess

from crds.pysh import usage

if len(sys.argv) > 2 and "--help" in sys.argv:
    del sys.argv[2]
    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 command line wrapper that replaces the "python -m" syntax
for invoking CRDS programs.

For example,  the new preferred syntax:

    crds list --status ...

is equivalent to the legacy native Python syntax:

    python -m crds.list --status ...

NOTE: For some commands the package path has changed so the legacy syntax can
no longer supported.  The "crds" wrapper is aware of the new paths and should
be used instead universally.

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

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",
}

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)


