use std::{env, process::Command};

fn main() {
    println!("cargo:rerun-if-env-changed=RUSTC");

    if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("linux")
        || env::var("PROFILE").as_deref() != Ok("debug")
    {
        return;
    }

    let rustc = env::var_os("RUSTC").unwrap_or_else(|| "rustc".into());
    let target = env::var("TARGET").expect("Cargo must provide the build target");
    let output = Command::new(rustc)
        .args(["--target", &target, "--print", "target-libdir"])
        .output()
        .expect("query Rust target library directory");
    assert!(
        output.status.success(),
        "rustc --print target-libdir failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let target_libdir =
        String::from_utf8(output.stdout).expect("Rust target library directory must be UTF-8");

    println!(
        "cargo:rustc-link-arg-bin=bds-cli=-Wl,-rpath,{}",
        target_libdir.trim()
    );
}
