use std::{env, process::Command};

const VERSION_MAJOR: &str = env!("CARGO_PKG_VERSION_MAJOR");
const VERSION_MINOR: &str = env!("CARGO_PKG_VERSION_MINOR");
const VERSION_PATCH: &str = env!("CARGO_PKG_VERSION_PATCH");
const MANIFEST_DIR: &str = env!("CARGO_MANIFEST_DIR");
const AUTOGEN_WARNING: &str = "/* This file is automatically generated, do not modify */";

fn main() {
    println!(
        "cargo:rustc-cdylib-link-arg=-Wl,-soname,libfdo_data.so.{}",
        VERSION_MAJOR
    );

    cbindgen::Builder::new()
        .with_crate(MANIFEST_DIR)
        .with_parse_deps(true)
        .with_parse_include(&["fdo-data-formats"])
        .with_include_version(true)
        .with_include_guard("FDO_DATA_H")
        .with_after_include(format!(
            "\n#define FDO_DATA_MAJOR {}\n#define FDO_DATA_MINOR {}\n#define FDO_DATA_PATCH {}",
            VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH
        ))
        .with_pragma_once(true)
        .with_autogen_warning(AUTOGEN_WARNING)
        .with_style(cbindgen::Style::Both)
        .with_item_prefix("Fdo")
        .with_documentation(true)
        .with_language(cbindgen::Language::C)
        .generate()
        .expect("Unable to generate bindings")
        .write_to_file("fdo_data.h");

    // Generate the Go bindings documentation
    let manifest_dir = std::path::PathBuf::from(MANIFEST_DIR);
    let godoc = Command::new("go")
        .args(&["doc", "-all"])
        .current_dir(
            manifest_dir
                .join("../libfdo-data-go")
                .canonicalize()
                .unwrap(),
        )
        .output()
        .expect("Unable to generate Go bindings documentation");
    let godoc = String::from_utf8(godoc.stdout).unwrap();
    let godoc = format!(
        "{}
/*
 * This file is intended to detect API changes during CI.
 * DO commit changes to this file.
 */
{}",
        AUTOGEN_WARNING, godoc
    );

    std::fs::write(manifest_dir.join("libfdo-data-go.doc"), godoc.as_bytes())
        .expect("Unable to write Go bindings documentation");
}
