//! Main build script entry point.
//!
//! This file serves as the entry point for C++ dependencies building

mod extension;
mod leveldb;
mod linker;
mod snappy;
mod zstd;

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

/// Directory name within `$OUT_DIR` where the static libraries should be built.
pub const LIB_DIR: &str = "lib";
pub const CXX_STANDARD: &str = "17";
pub const C_STANDARD: &str = "11";

/// Initialize build environment and return the library installation directory.
fn get_install_dir() -> PathBuf {
    let outdir = env::var("OUT_DIR").unwrap();
    std::path::Path::new(&outdir).join(LIB_DIR)
}

fn set_cmake_env() {
    let build_type = match env::var("PROFILE")
        .iter()
        .find(|s| s.eq_ignore_ascii_case("release"))
    {
        Some(_) => "Release",
        None => "Debug",
    };
    unsafe {
        env::set_var("CMAKE_BUILD_TYPE", build_type);
        env::set_var("CMAKE_BUILD_PARALLEL_LEVEL", num_cpus::get().to_string());
    }
}

fn main() {
    println!("[build] Started");
    set_cmake_env();

    let install_dir = get_install_dir();
    println!("cargo:rustc-link-search=native={}", &install_dir.display());

    #[cfg(feature = "snappy")]
    let snappy_prefix = Some(snappy::build(&install_dir));
    #[cfg(not(feature = "snappy"))]
    let snappy_prefix: Option<std::path::PathBuf> = None;

    #[cfg(feature = "zstd")]
    let zstd_prefix = Some(zstd::build(&install_dir));
    #[cfg(not(feature = "zstd"))]
    let zstd_prefix: Option<std::path::PathBuf> = None;

    #[allow(unused)]
    let leveldb_prefix = leveldb::build(&install_dir, snappy_prefix, zstd_prefix);

    // Conditionally build extension if logger feature is enabled
    #[cfg(feature = "logger")]
    extension::build(&install_dir, &leveldb_prefix);

    linker::configure();
    println!("[build] Finished");
}
