//
// Syd: rock-solid unikernel
// src/syd-size.rs: Given a number, print human-formatted size and exit.
//                  Given a string, parse human-formatted size into bytes, print and exit.
//
// Copyright (c) 2024 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0-or-later

use std::process::ExitCode;

use syd::err::SydResult;

// Set global allocator to mimalloc.
#[global_allocator]
static GLOBAL: mimalloc2_rust::GlobalMiMalloc = mimalloc2_rust::GlobalMiMalloc;

fn main() -> SydResult<ExitCode> {
    syd::set_sigpipe_dfl()?;

    // Configure mimalloc.
    syd::configure_mimalloc();

    let mut args = std::env::args();

    match args.nth(1).as_deref() {
        None | Some("-h") => {
            println!("Usage: syd-size size");
            println!("Given a number, print human-formatted size and exit.");
            println!("Given a string, parse human-formatted size into bytes, print and exit.");
        }
        Some(value) => {
            if value.chars().all(|c| c.is_ascii_digit()) {
                match value.parse::<usize>() {
                    Ok(size) => {
                        println!("{}", syd::human_size(size));
                    }
                    Err(error) => {
                        eprintln!("Failed to parse: {error}");
                        return Ok(ExitCode::FAILURE);
                    }
                }
            } else {
                match parse_size::Config::new().with_binary().parse_size(value) {
                    Ok(size) => {
                        println!("{size}");
                    }
                    Err(error) => {
                        eprintln!("Failed to parse: {error}");
                        return Ok(ExitCode::FAILURE);
                    }
                }
            }
        }
    }

    Ok(ExitCode::SUCCESS)
}
