#!/usr/bin/python -O

from os import stat
from sys import argv, stderr

# Once we require Python 2.5+, the following can be simplified to just
# the "from ... import" statement with no ImportError fallback.
try:
    from subprocess import CalledProcessError, check_call
except ImportError:

    from subprocess import call

    class CalledProcessError(Exception):
        def __init__(self, returncode, cmd):
            self.returncode = returncode
            self.cmd = cmd

    def check_call(*popenargs, **kwargs):
        retcode = call(*popenargs, **kwargs)
        cmd = kwargs.get('args')
        if cmd is None:
            cmd = popenargs[0]
        if retcode:
            raise CalledProcessError(retcode, cmd)
        return retcode



def run_stage(command, verbose):
    if verbose:
        print >>stderr, "  %s" % ' '.join(command)

    retcode = check_call(command)
    if retcode != 0:
        raise OSError(retcode, command)


def add_section(name, source):
    if source and stat(source).st_size > 0:
        return ['--add-section', '.debug_%s=%s' % (name, source)]
    else:
        return []


def main():
    asm = ['/usr/bin/as']

    verbose = False
    outfile = None

    saved_cfg = None
    saved_dataflow = None
    saved_site_info = None
    saved_implications = None

    args = argv[1:]
    while args:
        arg = args.pop(0)

         # Sampler Options
        if arg == '-fsave-blast-spec':
            args.pop(0)
        elif arg == '-fsave-cfg':
            saved_cfg = args.pop(0)
        elif arg == '-fsave-dataflow':
            saved_dataflow = args.pop(0)
        elif arg == '-fsave-site-info':
            saved_site_info = args.pop(0)
        elif arg == '-fsave-implications':
            saved_implications = args.pop(0)

         # Overall Options
        elif arg == '-o':
            outfile = args.pop(0)
            asm += [arg, outfile]
        elif arg == '--verbose':
            verbose = True
        else:
            asm.append(arg)

    run_stage(asm, verbose)

    objcopy = []
    objcopy += add_section('sampler_cfg', saved_cfg)
    objcopy += add_section('site_info', saved_site_info)
    objcopy += add_section('sampler_dataflow', saved_dataflow)
    objcopy += add_section('sampler_implications', saved_implications)
    if objcopy and outfile:
        run_stage(['/usr/bin/objcopy'] + objcopy + [outfile], verbose)


if __name__ == '__main__':
    try:
        main()
    except CalledProcessError, error:
        exit(error.returncode)
