#!/usr/bin/env qore

/** Used to compile all Java sources in a directory tree to class files and then create a jar from the built classes

    Arguments not explicitly processed by this script should be in the format accepted by javac; all unrecognized
    arguments are passed directly as-is to the compiler
*/

%new-style
%require-types
%strict-args
%enable-all-warnings

# automatically set up CLASSPATH to required jars
%module-cmd(jni) add-relative-classpath ../share/qore/java/qore-jni.jar
%module-cmd(jni) add-relative-classpath ../share/qore/java/qore-jni-compiler.jar

%module-cmd(jni) import org.qore.jni.compiler.QoreJavaCompiler
%module-cmd(jni) import org.qore.jni.compiler.QoreJavaCompilerException
%module-cmd(jni) import org.qore.jni.compiler.CompilerOutput
%module-cmd(jni) import java.io.InputStream
%module-cmd(jni) import java.io.FileOutputStream

%requires Util

%exec-class QJava2Jar

class QJava2Jar {
    public {
        hash<auto> opts;
        string start_dir;
        list<string> source_paths();
        string jar_path;

        const ERR_COMPILATION_FAILURE = 1;
        const ERR_INVALID_SOURCE      = 2;
        const ERR_NO_SOURCES          = 3;

        const BufSize = 16384;

        # fixed ISO-8601 timestamp applied to all jar entries so that rebuilding from unchanged
        # sources produces byte-identical jars; this prevents the generated provider jars (which are
        # committed to the source tree and overwritten by the build) from showing as modified after
        # every build (must be in the range 1980-01-01..2099-12-31 accepted by "jar --date")
        const JarEntryDate = "2026-01-01T00:00:00Z";
    }

    constructor() {
        parseOptions();
        if (!source_paths || !jar_path) {
            usage();
            set_return_value(0);
            return;
        }
        start_dir = source_paths[0];

        hash<string, string> srcs;
        foreach string path in (source_paths) {
            processPath(\srcs, path);
        }

        if (!srcs) {
            if (!opts.quiet) {
                error(ERR_NO_SOURCES, "no sources to compile");
            }
            set_return_value(1);
            return;
        }

        if (!opts.quiet) {
            map printf("%s: %d bytes source\n", $1.key, $1.value.size()), srcs.pairIterator();
        }

        if (hstat(start_dir).type == "REGULAR") {
            start_dir = dirname(start_dir);
        }

        QoreJavaCompiler compiler(ARGV);
        DiagnosticCollector diags();
        on_error
            map printf("%s\n", $1),
                QoreJavaCompilerException::extractDiagnosticMessages(diags);
        # jar entry names collected here and sorted before jar creation so that entry order is
        # deterministic regardless of the compiler's output map iteration order
        list<string> jar_entries();
        # track class file paths for cleanup after jar creation
        list<string> class_file_paths();
        hash<string, CompilerOutput> cv = compiler.compile(srcs, diags);
        string base_dir;
        foreach hash<auto> i in (cv.pairIterator()) {
            string class_file_name = i.key;
            class_file_name =~ s/\./\//g;
            class_file_name += ".class";
            string fn;
            if (opts.output_dir) {
                fn = opts.output_dir + "/" + class_file_name;
            } else if (base_dir) {
                fn = base_dir + class_file_name;
            } else if (class_file_name =~ /\// && (string dir = dirname(class_file_name))
                && (regex(start_dir, dir + "$"))) {
                if (opts.root) {
                    fn = opts.root + "/" + class_file_name;
                } else {
                    base_dir = start_dir;
                    splice base_dir, -dir.length();
                    fn = base_dir + class_file_name;
                }
            } else {
                fn = (opts.root ?? start_dir) + "/" + class_file_name;
            }
            io::InputStream stream = i.value.file.openInputStream();
            on_exit stream.close();

            # create parent directories if they don't exist
            string parent_dir = dirname(fn);
            if (!is_dir(parent_dir)) {
                try {
                    mkdir_ex(parent_dir, 0755, True);
                } catch (hash<ExceptionInfo> ex) {
                    if (ex.err == "DIR-CREATE-FAILURE" && ex.arg == 17) {
                        # EEXIST on an intermediate directory (race condition with parallel builds);
                        # retry - the blocking intermediate dir now exists, so the retry will create
                        # remaining subdirectories
                        if (!is_dir(parent_dir)) {
                            mkdir_ex(parent_dir, 0755, True);
                        }
                    } else {
                        rethrow;
                    }
                }
            }

            io::File targetFile(fn);
            io::FileOutputStream outStream(targetFile);
            on_exit outStream.close();

            while (binary b = stream.readNBytes(BufSize)) {
                outStream.write(b, 0, b.size());
            }

            # must escape "$" chars in the name
            class_file_name = sprintf("%y", class_file_name);
            class_file_name =~ s/\$/\\$/g;
            jar_entries += class_file_name;
            class_file_paths += fn;
            if (!opts.quiet) {
                printf("wrote: %y\n", fn);
            }
        }

        # create jar file
        if (!absolute_path(jar_path)) {
            jar_path = normalize_dir(getcwd() + "/" + jar_path);
        }
        chdir(opts.output_dir ?? opts.root ?? base_dir ?? start_dir);
        # sort entries for a deterministic archive order and pin a fixed entry timestamp with
        # "--date" (requires the GNU long-form options; the legacy "cf"/"cvf" syntax does not accept
        # "--date") so that rebuilds from unchanged sources are byte-identical
        string file_list = join(" ", sort(jar_entries));
        string verbose = opts.quiet ? "" : " --verbose";
        string cmd = sprintf("jar --create%s --file %y --date=%s %s", verbose, jar_path,
            JarEntryDate, file_list);
        if (!opts.quiet) {
            printf("cmd: %y\n", cmd);
        }
        int rc = system(cmd);
        if (rc) {
            stderr.printf("ERROR: jar command failed with exit code %d: %s\n", rc, cmd);
            exit(ERR_COMPILATION_FAILURE);
        }
        if (!opts.quiet) {
            printf("created %y: %d file%s\n", jar_path, cv.size(), cv.size() == 1 ? "" : "s");
        }

        # clean up intermediate .class files to prevent the JVM's system classloader from
        # picking them up (its default classpath is "." which can conflict with our custom
        # classloader's dynamic class generation)
        foreach string cfp in (class_file_paths) {
            unlink(cfp);
        }
    }

    processPath(reference<hash<string, string>> srcs, string path, *string root, *bool ignore_invalid) {
        *hash<StatInfo> h = hstat(path);
        if (!h) {
            error(ERR_INVALID_SOURCE, "%s: %s", path, strerror());
        }
        if (h.type == "DIRECTORY") {
            if (!exists root) {
                root = path;
            }
            scanDir(\srcs, path, root);
            return;
        }
        if (h.type != "REGULAR") {
            if (ignore_invalid) {
                return;
            }
            error(ERR_INVALID_SOURCE, "%s: path is type %y; require \"REGULAR\" or \"DIRECTORY\"", path, h.type);
        }
        if (path !~ /\.java$/) {
            if (ignore_invalid) {
                return;
            }
            error(ERR_INVALID_SOURCE, "%s: can only handle .java files", path);
        }
        string key;
        if (opts.root) {
            if (path.equalPartialPath(opts.root)) {
                key = path[opts.root.length() + 1..];
                key =~ s/\/+/\//g;
            } else {
                throw "INVALID-PATH", sprintf("root path is %y which is not a prefix of %y", opts.root, path);
            }
        } else if (exists root) {
            key = path[root.length() + 1..];
        } else {
            key = basename(path);
        }

        key =~ s/\.java//;
        key =~ s/\//./g;

        srcs{key} = File::readTextFile(path);
    }

    scanDir(reference<hash<string, string>> srcs, string path, string root) {
        map processPath(\srcs, $1, root, True), glob(path + "/*");
    }

    error(int err, string fmt) {
        if (!opts.quiet) {
            stderr.printf("ERROR: %s\n", vsprintf(fmt, argv));
        }
        exit(err);
    }

    parseOptions() {
        int l = ARGV.size();
        # scan for classpath
        for (int i = 0; i < l; ++i) {
            if (ARGV[i] == "-cp") {
                Program::issueModuleCmd("jni", "add-classpath " + ARGV[i + 1]);
            }
        }

        for (int i = 0; i < l; ) {
            string arg = ARGV[i];
            if (arg == "-h" || arg == "--help") {
                QJava2Jar::usage();
                exit(0);
            }
            if (arg == "-q" || arg == "--quiet") {
                opts.quiet = True;
                splice ARGV, i, 1;
                --l;
                continue;
            }
            if (arg == "-r") {
                opts.root = ARGV[i + 1];
                splice ARGV, i, 2;
                l -= 2;
                continue;
            }
            if (arg == "--root") {
                opts.root = ARGV[i + 1];
                splice ARGV, i, 2;
                l -= 2;
                continue;
            }
            if (*string root = (arg =~ x/^-r=?(.*)/[0])) {
                opts.root = root;
                splice ARGV, i, 1;
                --l;
                continue;
            }
            if (*string root = (arg =~ x/^--root=?(.*)/[0])) {
                opts.root = root;
                splice ARGV, i, 1;
                --l;
                continue;
            }
            if (arg == "-d") {
                opts.output_dir = ARGV[i + 1];
                splice ARGV, i, 2;
                l -= 2;
                continue;
            }
            if (arg == "--output-dir") {
                opts.output_dir = ARGV[i + 1];
                splice ARGV, i, 2;
                l -= 2;
                continue;
            }
            if (*string output_dir = (arg =~ x/^-d=?(.*)/[0])) {
                opts.output_dir = output_dir;
                splice ARGV, i, 1;
                --l;
                continue;
            }
            if (*string output_dir = (arg =~ x/^--output-dir=?(.*)/[0])) {
                opts.output_dir = output_dir;
                splice ARGV, i, 1;
                --l;
                continue;
            }
            if (arg == "-cp") {
                # skip -cp and its value; they stay in ARGV for QoreJavaCompiler
                i += 2;
                continue;
            }
            if (arg[0] != "-") {
                if (jar_path) {
                    source_paths += (extract ARGV, i, 1)[0];
                    --l;
                    continue;
                }
                jar_path = (extract ARGV, i, 1)[0];
                --l;
                continue;
            }
            ++i;
        }
    }

    static usage() {
        printf("%s: <jar name> <source directory>\n"
            " -d,--output-dir=ARG  set the output dir for class files (default: source root)\n"
            " -r,--root=ARG        set the root dir for finding sources\n"
            " -q,--quiet           suppress output\n"
            " -h,--help            this help text\n"
            "\nCompiles all java sources in the given source directory tree to class files and packages\n"
            "the class files in a jar file.\n"
            "\n*NOTE*: Arguments not explicitly listed above should be in the format accepted by javac;\n"
              "        all unrecognized arguments are passed unmodified to the compiler\n",
            get_script_name()
        );
    }
}
