//! Build script for quicproquo-proto.
//!
//! Invokes the `capnp` compiler to generate Rust types from `.capnp` schemas
//! located in the workspace-root `schemas/` directory.
//!
//! # Prerequisites
//!
//! The `capnp` CLI must be installed and on `PATH`.
//!
//! Debian/Ubuntu:  apt-get install capnproto
//! macOS:          brew install capnp
//! Docker:         see docker/Dockerfile

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

fn main() {
    let manifest_dir =
        PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set by Cargo"));

    // Workspace root is two levels above this crate (quicproquo/crates/quicproquo-proto).
    let workspace_root = manifest_dir
        .join("../..")
        .canonicalize()
        .expect("could not canonicalize workspace root path");

    let schemas_dir = workspace_root.join("schemas");

    // Re-run this build script whenever any schema file changes.
    println!(
        "cargo:rerun-if-changed={}",
        schemas_dir.join("auth.capnp").display()
    );
    println!(
        "cargo:rerun-if-changed={}",
        schemas_dir.join("delivery.capnp").display()
    );
    println!(
        "cargo:rerun-if-changed={}",
        schemas_dir.join("node.capnp").display()
    );
    println!(
        "cargo:rerun-if-changed={}",
        schemas_dir.join("federation.capnp").display()
    );

    capnpc::CompilerCommand::new()
        // Treat `schemas/` as the include root so that inter-schema imports
        // resolve correctly.
        .src_prefix(&schemas_dir)
        .file(schemas_dir.join("auth.capnp"))
        .file(schemas_dir.join("delivery.capnp"))
        .file(schemas_dir.join("node.capnp"))
        .file(schemas_dir.join("federation.capnp"))
        .run()
        .expect(
            "Cap'n Proto schema compilation failed. \
             Is `capnp` installed? (apt-get install capnproto / brew install capnp)",
        );
}
