#! /usr/bin/python
#
# Emulate the gccxml command using castxml.
# Expect command line: gccxml [options] <input-file> -fxml=<output-file>
#

import os, sys

fail = False
banner = "GCC-XML compatibility CastXML wrapper"

def error(msg):
    print banner
    print "Error:", msg
    global fail
    fail = True

def usage():
    print banner
    print """Usage: gccxml [options] <input-file> -fxml=<output-file>

Note: not all the gccxml options are supported.
The real gccxml (not compatible with GCC 5) is available as gccxml.real.

"""

# Map from option name to number of arguments
option_args = {
    "--copyright" : 0,
    "--debug" : 0,
    "--gccxml-compiler" : 1,
    "--gccxml-cxxflags" : 1,
    "--gccxml-executable" : 1,
    "--gccxml-cpp" : 1,
    "--gccxml-config" : 1,
    "--gccxml-root" : 1,
    "--gccxml-gcc-options" : 1,
    "--help-html" : 0,
    "--man" : 0,
    "--print" : 0,
    "--preprocess" : 0,
    "--version" : 0,
    }

unsupported_variables = [
    "GCCXML_COMPILER",
    "GCCXML_CXXFLAGS",
    "GCCXML_CONFIG",
    "GCCXML_EXECUTABLE",
    "GCCXML_CPP",
    "GCCXML_ROOT",
    "GCCXML_FLAGS",
    "GCCXML_USER_FLAGS",
]

def split_arg(prefix, arg):
    if not arg.startswith(prefix): return False
    index = len(prefix)
    return arg[index:]

if len(sys.argv) < 3:
    usage()
    sys.exit(1)

for v in unsupported_variables:
    if os.environ.get(v) is not None:
        error("unsupported environment variable: " + v)

castxml_cmd = ['/usr/bin/castxml']
infile = None
outfile = None

index = 1
while index < len(sys.argv):
    arg = sys.argv[index]
    if arg == "--help":
        usage()
        sys.exit(1)
    elif arg in option_args:
        error("unsupported argument: " + arg)
        index += option_args[arg]
    elif arg.startswith('-fxml='):
        outfile = split_arg('-fxml=', arg)
    elif arg.startswith('-fxml-start='):
        decl = arg[12:]
        castxml_cmd.append('--castxml-start')
        castxml_cmd.append(decl)
    elif arg.startswith('-'):
        castxml_cmd.append(arg)
    else:
        if infile:
            error("detected multiple input files")
        infile = arg
    index += 1

if not infile:
    error("no input file specified")
elif not outfile:
    error("no output file specified")
else:
    castxml_cmd.append(infile)
    castxml_cmd.append('--castxml-gccxml')
    castxml_cmd.append('-o')
    castxml_cmd.append(outfile)

if fail:
    sys.exit(1)

print(castxml_cmd)
sys.stdout.flush()
os.execv(castxml_cmd[0], castxml_cmd)
