//! Zstd compression library build module.

use super::C_STANDARD;
use crate::linker;
use std::path::{Path, PathBuf};

pub fn build(install_dir: &Path) -> PathBuf {
    println!("[zstd] Building");
    let mut config = cmake::Config::new(
        std::path::Path::new("deps")
            .join("zstd")
            .join("build")
            .join("cmake"),
    );
    config
        .define("CMAKE_C_STANDARD", C_STANDARD)
        .define("ZSTD_BUILD_STATIC", "ON")
        .define("ZSTD_BUILD_SHARED", "OFF")
        .define("ZSTD_BUILD_PROGRAMS", "OFF")
        .define("ZSTD_BUILD_TESTS", "OFF")
        .define("ZSTD_BUILD_CONTRIB", "OFF")
        .define("ZSTD_LEGACY_SUPPORT", "OFF")
        .define("CMAKE_INSTALL_LIBDIR", install_dir);
    linker::apply_cmake_flags(&mut config);

    let dest_prefix = config.build();
    assert_eq!(
        dest_prefix.join(install_dir.file_name().unwrap()),
        install_dir,
        "CMake should build Zstd in provided install_dir"
    );

    #[cfg(target_env = "msvc")]
    // Rename static lib name on Windows platform, because leveldb requires the lib name as `zstd` specifically
    {
        let zstd_static_lib = install_dir.join("zstd_static.lib");
        let zstd_lib = install_dir.join("zstd.lib");
        if zstd_static_lib.exists() {
            std::fs::rename(&zstd_static_lib, &zstd_lib)
                .expect("Failed to rename zstd_static.lib to zstd.lib");
        }
    }
    dest_prefix
}
