use std::{
    env,
    error::Error,
    path::PathBuf,
    process::{Command, Stdio},
};

fn main() -> Result<(), Box<dyn Error>> {
    println!("cargo::rerun-if-changed=src");

    let out_dir = env::var("OUT_DIR").unwrap();
    let out_path = PathBuf::from(&out_dir);
    let profile = env::var("PROFILE").unwrap();
    let target = env::var("TARGET").unwrap();

    // TODO: Use of PROFILE is discouraged, so we should switch this to a more fine-grained system
    // reading back from other environment variables.
    let optimize = match &profile[..] {
        "debug" => "Debug",
        "release" => "ReleaseSmall",
        _ => panic!("unknown profile"),
    };

    let color = match env::var("NO_COLOR").is_ok() {
        true => "off",
        false => "on",
    };

    let target = match &target[..] {
        "x86_64-unknown-linux-gnu" => "x86_64-linux-gnu",
        "aarch64-unknown-linux-gnu" => "aarch64-linux-gnu",
        other => {
            eprintln!("warning: unknown target {other:?}");
            &target
        }
    };

    let output = Command::new("zig")
        .arg("build")
        .arg("install")
        // Terminal output
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .arg("--prominent-compile-errors")
        .arg("--color")
        .arg(color)
        // Build output
        .arg("--cache-dir")
        .arg(out_path.join("zig-cache"))
        .arg("--prefix")
        .arg(out_path.join("zig-out"))
        // Build settings
        .arg(format!("-Doptimize={optimize}"))
        .arg(format!("-Dtarget={target}"))
        .output()?;

    if !output.status.success() {
        panic!("zig failed to build");
    }

    println!("cargo::rustc-link-search={out_dir}/zig-out/lib");
    println!("cargo::rustc-link-lib=haku2");

    Ok(())
}
