use std::{
    env,
    fs::File,
    io::{self, Read},
    path::Path,
    process::ExitCode,
};

use sha2::{Digest, Sha256};

fn do_digest<P: AsRef<Path>>(path: P) -> Result<(), io::Error> {
    let mut buf = [0; 32768];
    let mut file = File::open(path)?;
    let mut hasher = Sha256::new();

    loop {
        let count = file.read(&mut buf)?;
        if count == 0 {
            break;
        }
        hasher.update(&buf[..count]);
    }

    let result = hasher.finalize();
    for byte in result {
        print!("{:02x}", byte);
    }
    println!();
    Ok(())
}

fn main() -> ExitCode {
    let args: Vec<_> = env::args().collect();
    if args.len() != 2 {
        eprintln!("TODO: {} FILENAME", args[0]);
        return ExitCode::FAILURE;
    }

    match do_digest(&args[1]) {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("{}: {}", args[1], error);
            ExitCode::FAILURE
        }
    }
}
