use std::{os::unix::process::ExitStatusExt, process::Command};

fn main() {
    let output = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .output()
        .unwrap_or_else(|e| {
            eprintln!("Failed to execute git rev-parse command: {}", e);
            std::process::Output {
                status: std::process::ExitStatus::from_raw(1),
                stdout: Vec::new(),
                stderr: Vec::new(),
            }
        });

    let git_hash: String = String::from_utf8(output.stdout).unwrap_or_else(|e| {
        eprintln!("Failed to parse git hash as UTF-8: {}", e);
        String::new()
    });

    let git_short_hash = match git_hash.is_empty() {
        true => "".to_owned(),
        false => format!("_{}", git_hash.chars().take(8).collect::<String>()),
    };

    let output_status = Command::new("git")
        .args(["status", "--porcelain"])
        .output()
        .unwrap_or_else(|e| {
            eprintln!("Failed to execute git status command: {}", e);
            std::process::Output {
                status: std::process::ExitStatus::from_raw(1),
                stdout: Vec::new(),
                stderr: Vec::new(),
            }
        });
    let version_suffix = match !output_status.stdout.is_empty() {
        true => "_dirty",
        false => "",
    };

    println!("cargo:rustc-env=GIT_HASH={}", git_hash);
    // println!(
    //     "cargo:rustc-env=GIT_SHORT_HASH={}",
    //     git_short_hash + version_suffix
    // );
    println!(
        "cargo:rustc-env=GIT_VERSION_SUFFIX={}",
        git_short_hash + version_suffix
    );
}
