use std::env;
use std::path::PathBuf;

fn main() {
    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
    let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());

    let runtime_c = manifest_dir.join("runtime_nocrt.c");
    let start_c = manifest_dir.join("start_nocrt.c");

    if runtime_c.exists() {
        let mut build = cc::Build::new();
        build.file(&runtime_c);
        build.opt_level(2);
        build.out_dir(&out_dir);
        build.compile("runtime_nocrt");
        println!("cargo:rustc-link-search=native={}", out_dir.display());
    }

    if start_c.exists() {
        let mut build = cc::Build::new();
        build.file(&start_c);
        build.opt_level(2);
        build.out_dir(&out_dir);
        // 禁用 memcpy/memmove/memset 的内置函数优化，因为 start_nocrt.c 自己定义了这些函数
        build.flag("/Oi-");
        build.compile("start_nocrt");
    }

    println!("cargo:rerun-if-changed=runtime_nocrt.c");
    println!("cargo:rerun-if-changed=start_nocrt.c");
}
