//
// Build metaprogram for the jellyfin music player.
//
// Run with:   jai build.jai
//
// Adds ./modules to the import path so we can vendor Jaison and stb_image
// alongside the standard Jai modules.
//

#run build();

build :: () {
    set_build_options_dc(.{do_output = false});

    w := compiler_create_workspace("Player");
    if !w {
        compiler_report("Could not create workspace.");
        return;
    }

    options := get_build_options(w);
    copy_commonly_propagated_fields(get_build_options(), *options);

    options.output_executable_name = "player";
    options.output_path            = "build/";

    import_paths: [..] string;
    array_add(*import_paths, tprint("%modules", #filepath));
    for options.import_path array_add(*import_paths, it);
    options.import_path = import_paths;

    // Help the linker find libcurl.so. On a system where only libcurl.so.4 is
    // installed (no -dev package), we fall back to a symlink in ./lib/.
    extra_linker: [..] string;
    array_add(*extra_linker, tprint("-L%lib", #filepath));
    options.additional_linker_arguments = extra_linker;

    // Build the dr_mp3/dr_flac wrapper if the static lib is missing or stale.
    ensure_audio_decoders_built();

    set_build_options(options, w);

    make_directory_if_it_does_not_exist("build");

    compiler_begin_intercept(w);
    add_build_file(tprint("%src/main.jai", #filepath), w);
    compiler_end_intercept(w);
}

ensure_audio_decoders_built :: () {
    #if OS == .LINUX  out := tprint("%modules/audio_decoders/linux/decoders.a", #filepath);
    #if OS == .MACOS  out := tprint("%modules/audio_decoders/macos/decoders.a", #filepath);
    src := tprint("%modules/audio_decoders/source/decoders.c",       #filepath);
    script := tprint("%modules/audio_decoders/source/build.sh",      #filepath);

    if file_exists(out) {
        out_modtime, _, out_ok := file_modtime_and_size(out);
        src_modtime, _, src_ok := file_modtime_and_size(src);
        if out_ok && src_ok && compare_apollo_times(out_modtime, src_modtime) >= 0  return;
        log("audio_decoders: source newer than %, rebuilding\n", out);
    }

    result, output := run_command("/bin/sh", script, capture_and_return_output=true);
    if result.exit_code != 0 {
        compiler_report(tprint("audio_decoders build failed (exit=%):\n%", result.exit_code, output));
    }
}

#import "Basic";
#import "Compiler";
#import "File";
#import "File_Utilities";
#import "Process";
