/*
    Copyright: 2020 Rasmus Thomsen <oss@cogitri.dev>
    SPDX-License-Identifier: GPL-3.0-or-later
*/

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

fn main() {
    println!("cargo:rustc-link-lib=static=apk");
    if let Ok(lib_path) = env::var("APK_LIB_PATH") {
        println!("cargo:rustc-link-search=all={}", lib_path);
    } else {
        println!("cargo:rustc-link-search=all=/usr/lib/sdk/Cogitri/lib");
    }
    system_deps::Config::new()
        .probe()
        .expect("Couldn't find required system libraries");

    println!("cargo:rerun-if-changed=wrapper.h");

    let meson_source_root = std::env::var("MESON_SOURCE_ROOT")
        .expect("Couldn't find MESON_SOURCE_ROOT in env, are you running via meson?...");

    let bindings = bindgen::Builder::default()
        .header("src/wrapper.h")
        .clang_arg(format!(
            "-I{}",
            Path::new(&meson_source_root)
                .join("subprojects")
                .join("apk-tools")
                .join("src")
                .into_os_string()
                .into_string()
                .unwrap()
        ))
        .derive_copy(false)
        .derive_default(true)
        .size_t_is_usize(true)
        .rustfmt_bindings(false)
        .impl_debug(true)
        .blacklist_type("apk_package")
        .blacklist_type("max_align_t")
        .parse_callbacks(Box::new(bindgen::CargoCallbacks))
        .generate()
        .expect("Unable to generate bindings");

    let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
    bindings
        .write_to_file(out_path.join("bindings.rs"))
        .expect("Couldn't write bindings!");
}
