use vergen_git2::{BuildBuilder, CargoBuilder, Emitter, Git2Builder, RustcBuilder};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    const PROTO_FILES: &[&str] = &["proto/metadata.proto"];
    const GENERATED_DIR: &str = "generated";
    const GENERATED_PROTO_RS: &str = "generated/tici_shard.metadata.rs";
    const GENERATED_RS: &str = "generated/metadata.rs";

    std::fs::create_dir_all(GENERATED_DIR)?;
    let mut prost_config = prost_build::Config::new();
    prost_config.out_dir(GENERATED_DIR);
    prost_config.compile_protos(PROTO_FILES, &["proto"])?;
    if std::path::Path::new(GENERATED_RS).exists() {
        std::fs::remove_file(GENERATED_RS)?;
    }
    std::fs::rename(GENERATED_PROTO_RS, GENERATED_RS)?;

    let build = BuildBuilder::all_build()?;
    let cargo = CargoBuilder::all_cargo()?;
    let git2 = Git2Builder::all_git()?;
    let rustc = RustcBuilder::all_rustc()?;

    Emitter::default()
        .add_instructions(&build)?
        .add_instructions(&cargo)?
        .add_instructions(&git2)?
        .add_instructions(&rustc)?
        .emit()?;

    for proto in PROTO_FILES {
        println!("cargo:rerun-if-changed={proto}");
    }
    println!("cargo:rerun-if-changed=build.rs");

    Ok(())
}
