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

fn main() {
    let sources = Path::new("blink.v");

    // Tell cargo to invalidate the built crate whenever the wrapper changes
    println!(
        "{}",
        format!("cargo:rerun-if-changed={}", sources.to_string_lossy())
    );

    let output = Command::new("yosys-config")
        .args(&["--datdir/include"])
        .output()
        .expect("failed to get yosys include dir");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let include = stdout.trim();

    // Write the bindings to the $OUT_DIR/bindings.rs file.
    let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
    let design_cc = out_path.join("design.cc");
    Command::new("yosys")
        .args(&[
            "-p",
            &format!("write_cxxrtl -header {}", design_cc.to_string_lossy()),
        ])
        .args(sources)
        .status()
        .expect("failed generate cxxrtl code");

    cc::Build::new()
        .include(include)
        .cpp(true)
        .flag_if_supported("-std=c++14")
        .file(design_cc)
        .compile("design");
}