fn env(s: &str) -> String {
    std::env::var(s).unwrap()
}

// do yourself a favor if you can, don't use windows
fn main() {
    #[cfg(target_os = "windows")]
    {
        println!(concat!(
            "NOTE: Windows can't easily find what to execute for 'ceedling' (the build system for algorithms-c).\n",
            "You may need to set it's path in crates/algorithms/build.rs"
        ));

        std::process::Command::new("ceedling.bat")
            .arg("clobber")
            .current_dir("./algorithms-c/")
            .status()
            .expect("could not cleanup old algorithms-c files");
    }
    #[cfg(not(target_os = "windows"))]
    {
        std::process::Command::new("ceedling")
            .arg("clobber")
            .current_dir("./algorithms-c/")
            .status()
            .expect("could not cleanup old algorithms-c files");
    }

    #[cfg(target_os = "windows")]
    let mut cmd = std::process::Command::new("ceedling.bat");
    #[cfg(not(target_os = "windows"))]
    let mut cmd = std::process::Command::new("ceedling");

    let arch = env("CARGO_CFG_TARGET_ARCH");
    let pw = env("CARGO_CFG_TARGET_POINTER_WIDTH");
    let os = env("CARGO_CFG_TARGET_OS");

    if arch == "arm" && pw == "32" && os == "none" {
        cmd.env("CC", "arm-none-eabi-gcc")
            .env("AR", "arm-none-eabi-ar")
            .env("CC_FLAGS", "-march=armv6-m");
    } else if os == "linux" || os == "windows" {
        cmd.env("CC", "gcc").env("AR", "ar");
    } else {
        panic!("Unsupported build target")
    }

    println!("Cwd: {}", std::env::current_dir().unwrap().display());
    let status = cmd
        .arg("release")
        .current_dir("./algorithms-c")
        .status()
        .expect("could not make c stuff");
    if !status.success() {
        panic!("ceedling returned an error")
    }
    let cwd = std::env::current_dir().unwrap().display().to_string();
    let libpath_s = format!("{cwd}/algorithms-c/build/artifacts/release/libalgorithms.a");
    let libpath = std::path::Path::new(&libpath_s);
    assert!(libpath.exists());
    println!("cargo::rustc-link-lib=algorithms");
    println!("cargo::rerun-if-changed={cwd}/algorithms-c/src/");
    println!(
        "cargo::rustc-link-search={}",
        libpath.parent().unwrap().display()
    );
}
