use std::{
    env,
    io::{self, stdout, Read, Stdout, Write},
    process::ExitCode,
};

use sysutils::Input;

fn cat_file(stdout: &mut Stdout, path: &str) -> io::Result<()> {
    let mut buf = [0; 512];
    let mut reader = Input::open_str(path)?;

    loop {
        let count = reader.read(&mut buf)?;

        if count == 0 {
            return Ok(());
        }

        stdout.write_all(&buf[..count])?;
    }
}

fn main() -> ExitCode {
    let mut stdout = stdout();
    let mut exit = ExitCode::SUCCESS;

    let args = env::args().skip(1);

    if args.len() == 0 {
        if let Err(error) = cat_file(&mut stdout, "-") {
            eprintln!("<stdin>: {}", error);
            exit = ExitCode::FAILURE;
        }
    } else {
        for arg in env::args().skip(1) {
            if let Err(error) = cat_file(&mut stdout, &arg) {
                eprintln!("{}: {}", arg, error);
                exit = ExitCode::FAILURE;
            }
        }
    }

    exit
}
