use std::{env, fs, path::PathBuf};

fn main() {
    let out = PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR is not set"));

    let default = env::var_os("CARGO_FEATURE_MEMORY_DEFAULT").is_some();
    let spifi = env::var_os("CARGO_FEATURE_MEMORY_SPIFI").is_some();
    let memory = match (default, spifi) {
        (true, false) => "memory_default.x",
        (false, true) => "memory_spifi.x",
        (true, true) => {
            panic!("features `memory-default` and `memory-spifi` are mutually exclusive")
        }
        (false, false) => panic!("enable either `memory-default` or `memory-spifi`"),
    };

    fs::copy("link.x", out.join("link.x")).expect("failed to copy link.x");
    fs::copy("sections.lds", out.join("sections.lds")).expect("failed to copy sections.lds");
    fs::copy(memory, out.join("memory.x")).expect("failed to copy memory layout");

    println!("cargo:rustc-link-search={}", out.display());
    println!("cargo:rerun-if-changed=link.x");
    println!("cargo:rerun-if-changed=sections.lds");
    println!("cargo:rerun-if-changed=memory_default.x");
    println!("cargo:rerun-if-changed=memory_spifi.x");
}
