fn main() {
    if std::env::var("CARGO_CFG_TARGET_OS").unwrap() != "android" {
        return;
    }

    setup_x86_64_android_workaround();

    // for some reason if we don't explicitly add this argument, the library get linked in a way
    // its symbols are not exported, so they are still considered missing when loading
    // libonionmasq-mobile.so
    println!("cargo:rustc-link-arg=-lbionic-missing");

    cc::Build::new()
        .file("bionic-missing/all-missing.c")
        .include("bionic-missing/include/")
        .include("bionic-missing/src/internal")
        .include(include_arch())
        .flag("-Wno-parentheses")
        .flag("-Wno-sign-compare")
        .flag("-Wno-unused-parameter")
        .compile("libbionic-missing.a");
}

fn include_arch() -> &'static str {
    match std::env::var("CARGO_CFG_TARGET_ARCH").unwrap().as_str() {
        "arm" => "bionic-missing/arch/arm",
        "aarch64" => "bionic-missing/arch/aarch64",
        "x86" => "bionic-missing/arch/i386",
        "x86_64" => "bionic-missing/arch/x86_64",
        _ => unimplemented!(),
    }
}

/// Adds a temporary workaround for an issue with the Rust compiler and Android
/// in x86_64 devices: https://github.com/rust-lang/rust/issues/109717.
// NOTE(eta): The below function is stolen from matrix-rust-sdk under Apache 2.0 license.
fn setup_x86_64_android_workaround() {
    use std::env;

    let target_os = env::var("CARGO_CFG_TARGET_OS").expect("CARGO_CFG_TARGET_OS not set");
    let target_arch = env::var("CARGO_CFG_TARGET_ARCH").expect("CARGO_CFG_TARGET_ARCH not set");
    if target_arch == "x86_64" && target_os == "android" {
        let android_ndk_home = env::var("ANDROID_NDK").expect("ANDROID_NDK not set");
        let build_os = match env::consts::OS {
            "linux" => "linux",
            "macos" => "darwin",
            "windows" => "windows",
            _ => panic!(
                "Unsupported OS. You must use either Linux, MacOS or Windows to build the crate."
            ),
        };
        const DEFAULT_CLANG_VERSION: &str = "14.0.7";
        let clang_version =
            env::var("NDK_CLANG_VERSION").unwrap_or_else(|_| DEFAULT_CLANG_VERSION.to_owned());
        let linux_x86_64_lib_dir = format!(
            "toolchains/llvm/prebuilt/{build_os}-x86_64/lib64/clang/{clang_version}/lib/linux/"
        );
        println!("cargo:rustc-link-search={android_ndk_home}/{linux_x86_64_lib_dir}");
        println!("cargo:rustc-link-lib=static=clang_rt.builtins-x86_64-android");
    }
}
