//! Build configuration and linker utilities.
use std::env;

#[cfg(target_env = "msvc")]
const LIB_PREFIX: &str = "/LIBPATH:";
#[cfg(not(target_env = "msvc"))]
const LIB_PREFIX: &str = "-L";

pub fn set_ldflags(lib_paths: &[String]) {
    if lib_paths.is_empty() {
        return;
    }
    let ldflags = lib_paths
        .iter()
        .map(|path| format!("{}{}", LIB_PREFIX, path))
        .collect::<Vec<_>>()
        .join(" ");

    unsafe {
        env::set_var("LDFLAGS", ldflags);
    }
}

/// Check if the enable_lto feature is enabled.
fn is_lto_enabled() -> bool {
    env::var("CARGO_FEATURE_ENABLE_LTO").is_ok()
}

/// Apply LTO compiler flags if enabled.
pub fn apply_cmake_flags(config: &mut cmake::Config) {
    if is_lto_enabled() {
        println!("[build] LTO optimization enabled");
        config
            .cxxflag("-flto")
            .cxxflag("-ffat-lto-objects")
            .cflag("-flto");
    } else {
        println!("[build] LTO optimization disabled");
    }
}

/// Configure platform-specific C++ library linking.
fn configure_cpp_linking() {
    #[cfg(feature = "logger")]
    println!("cargo:rustc-link-lib=static=leveldb_extension");
    println!("cargo:rustc-link-lib=static=leveldb");
    #[cfg(feature = "zstd")]
    println!("cargo:rustc-link-lib=static=zstd");
    #[cfg(feature = "snappy")]
    println!("cargo:rustc-link-lib=static=snappy");

    let target = env::var("TARGET").unwrap();
    if target.contains("apple") || target.contains("freebsd") {
        println!("cargo:rustc-link-lib=c++");
    } else if target.contains("gnu") || target.contains("netbsd") || target.contains("openbsd") {
        println!("cargo:rustc-link-lib=stdc++");
    } else if target.contains("musl") {
        // We want to link to libstdc++ *statically*. This requires that the user passes the right
        // search path to rustc via `-Lstatic=/path/to/libstdc++`.
        println!("cargo:rustc-link-lib=static=stdc++");
    }
}

pub fn configure() {
    // Apply LTO linker flags if enabled.
    if is_lto_enabled() {
        println!("cargo:rustc-link-arg=-flto");
    }
    configure_cpp_linking()
}
