//
// Syd: rock-solid application kernel
// src/utils/syd-cpu.rs: Print the number of CPUs.
//
// Copyright (c) 2024, 2025, 2026 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

use std::process::ExitCode;

// Set global allocator to GrapheneOS allocator.
#[cfg(all(
    not(coverage),
    not(feature = "prof"),
    not(target_os = "android"),
    not(target_arch = "riscv64"),
    target_page_size_4k,
    target_pointer_width = "64"
))]
#[global_allocator]
static GLOBAL: hardened_malloc::HardenedMalloc = hardened_malloc::HardenedMalloc;

// Set global allocator to tcmalloc if profiling is enabled.
#[cfg(feature = "prof")]
#[global_allocator]
static GLOBAL: tcmalloc::TCMalloc = tcmalloc::TCMalloc;

syd::main! {
    use lexopt::prelude::*;

    syd::set_sigpipe_dfl()?;

    // Parse CLI options.
    let mut opt_physical = false;

    let mut parser = lexopt::Parser::from_env();
    while let Some(arg) = parser.next()? {
        match arg {
            Short('h') => {
                help();
                return Ok(ExitCode::SUCCESS);
            }
            Short('l') => opt_physical = false,
            Short('p') => opt_physical = true,
            _ => return Err(arg.unexpected().into()),
        }
    }

    let num = if opt_physical {
        num_cpus::get_physical()
    } else {
        num_cpus::get()
    };
    println!("{num}");

    Ok(ExitCode::SUCCESS)
}

fn help() {
    println!("Usage: syd-cpu [-hlp]");
    println!("Print the number of CPUs.");
    println!("Use -l to print the number of logical CPUs (default).");
    println!("Use -p to print the number of physical CPUs.");
}
