use std::process::Command;

fn git(args: &[&str]) -> String {
    let output = Command::new("git")
        .args(args)
        .output()
        .expect("failed to execute git");

    if !output.status.success() {
        panic!("git command failed: git {}", args.join(" "));
    }

    String::from_utf8(output.stdout)
        .expect("git output not utf8")
        .trim()
        .to_string()
}

fn main() {
    // Re-run if HEAD changes
    println!("cargo:rerun-if-changed=.git/HEAD");
    println!("cargo:rerun-if-changed=.git/refs");

    let git_hash = git(&["rev-parse", "HEAD"]);
    let git_hash_short = git(&["rev-parse", "--short", "HEAD"]);

    let git_dirty = {
        let status = Command::new("git")
            .args(["diff", "--quiet"])
            .status()
            .expect("failed to check git dirty state");

        if status.success() { false } else { true }
    };

    println!("cargo:rustc-env=GIT_HASH={git_hash}");
    println!("cargo:rustc-env=GIT_HASH_SHORT={git_hash_short}");
    if git_dirty {
        println!("cargo:rustc-env=GIT_DIRTY=1");
    }
}
