#!/usr/bin/env python

## Copyright (C) 2005, 2006 Red Hat, Inc.
## Written by Gary Benson <gbenson@redhat.com>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.

import aotcompile
import os
import sys

def libdir():
    cmd = "%s -p" % aotcompile.PATHS["dbtool"]
    dir = os.path.abspath(os.popen(cmd, "r").readline().rstrip())
    dir, base = os.path.split(dir)
    if base != "classmap.db":
        raise aotcompile.Error, "%s: unexpected output" % cmd
    dir, base = os.path.split(dir)
    if not base.startswith("gcj-"):
        raise aotcompile.Error, "%s: unexpected output" % cmd
    return dir

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)
