extern crate dotenv;

use std::env;
use std::path::PathBuf;

fn main() {
    // Load the .env.build file for build-time environment variables
    let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
    let manifest_path = PathBuf::from(manifest_dir);
    dotenv::from_path(manifest_path.join(".env.build")).ok();

    println!("cargo::rerun-if-env-changed=SESAM_FSV_LIB_PATH");
    println!("cargo::rerun-if-env-changed=SESAM_FSV_SSVLIB");
    println!("cargo::rerun-if-changed=.env.build");
    println!("cargo::rerun-if-changed=build.rs");

    // Add local lib directory to the linker search path (for def files and static libs)
    let static_lib_path = manifest_path.join("lib");
    println!("cargo::rustc-link-search=native={}", static_lib_path.display());

    // Add the SESAM_FSV_LIB_PATH to the linker search path
    let fsv_lib_path = PathBuf::from(env::var("SESAM_FSV_LIB_PATH").unwrap());
    println!("cargo::rustc-link-search=native={}", fsv_lib_path.display());

    // Add the SESAM_FSV_LIB_PATH to the PATH environment variable
    if cfg!(target_os = "windows") {
        let path = env::var("PATH").unwrap_or(String::new());
        println!("cargo:rustc-env=PATH={};{}", fsv_lib_path.display(), path);
    } else if cfg!(target_os = "linux") {
        println!("cargo:rustc-env=LD_LIBRARY_PATH={}", fsv_lib_path.display());
    }

    // Link the SESAM_FSV_SSVLIB dynamic library
    println!("cargo::rustc-link-lib=dylib={}", env::var("SESAM_FSV_SSVLIB").unwrap());
    // TODO : try `raw-dylib` instead of `dylib` on Windows to avoid the need of the `lib` headers compiled from the `def`
}
