use std::fs;
use std::path::Path;

fn main() {
    println!("cargo:rerun-if-changed=debian/changelog");

    let version = changelog_version(Path::new("debian/changelog"))
        .unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string());

    println!("cargo:rustc-env=PATCH_BUILD_VERSION={version}");
}

fn changelog_version(path: &Path) -> Option<String> {
    let binding = fs::read_to_string(path).ok()?;
    let first_line = binding.lines().next()?.trim();
    let start = first_line.find('(')? + 1;
    let end = first_line[start..].find(')')? + start;
    Some(first_line[start..end].to_string())
}