#!/usr/bin/env python

import aotcompile
import os
import sys

LIBDIR = "/usr/lib/gcj"

try:
    name = os.environ.get("RPM_PACKAGE_NAME")
    if name is None:
        raise aotcompile.Error, "not for use outside rpm specfiles"
    arch = os.environ.get("RPM_ARCH")
    if arch == "noarch":
        raise aotcompile.Error, "cannot be used on noarch packages"
    srcdir = os.environ.get("RPM_BUILD_ROOT")
    if srcdir in (None, "/"):
        raise aotcompile.Error, "bad $RPM_BUILD_ROOT"
    dstdir = os.path.join(srcdir, LIBDIR.strip(os.sep), name)

    compiler = aotcompile.Compiler(srcdir, dstdir)
    compiler.gcjflags[0:0] = os.environ.get("RPM_OPT_FLAGS", "").split() 

    # XXX: This script should not accept options, because having
    # them it cannot be integrated into rpm.  But, gcj cannot
    # build each and every jarfile yet, so we must be able to
    # exclude until it can.
    # XXX --exclude is also used in the jonas rpm to stop
    # everything being made a subset of the mammoth client
    # jarfile. Should adjust the subset checker's bias to
    # favour many small jarfiles over one big one.
    try:
        options, exclusions = sys.argv[1:], []
        while options:
            if options.pop(0) != "--exclude":
                raise ValueError
            compiler.exclusions.append(
                os.path.join(srcdir, options.pop(0).lstrip(os.sep)))
    except:
        print >>sys.stderr, "usage: %s [--exclude PATH]..." % (
            os.path.basename(sys.argv[0]))
        sys.exit(1)

    compiler.compile()

except aotcompile.Error, e:
    print >>sys.stderr, "%s: error: %s" % (
        os.path.basename(sys.argv[0]), e)
    sys.exit(1)
