//
// Syd: rock-solid application kernel
// src/syd-info.rs: Print system information.
//
// Copyright (c) 2024, 2025 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

use std::{mem::MaybeUninit, process::ExitCode};

use nix::errno::Errno;
use serde_json::json;
use syd::err::SydResult;

fn main() -> SydResult<ExitCode> {
    use lexopt::prelude::*;

    syd::set_sigpipe_dfl()?;

    // Parse CLI options.
    let mut parser = lexopt::Parser::from_env();
    #[allow(clippy::never_loop)]
    while let Some(arg) = parser.next()? {
        match arg {
            Short('h') => {
                help();
                return Ok(ExitCode::SUCCESS);
            }
            _ => return Err(arg.unexpected().into()),
        }
    }

    let mut info = MaybeUninit::<libc::sysinfo>::uninit();
    // SAFETY: In libc we trust.
    Errno::result(unsafe { libc::sysinfo(info.as_mut_ptr()) })?;
    // SAFETY: sysinfo() has initialized `info` if it succeeded.
    let info = unsafe { info.assume_init() };

    #[allow(clippy::disallowed_methods)]
    let info = json!({
        "uptime": info.uptime,
        "loads": info.loads,
        "totalram": info.totalram,
        "freeram": info.freeram,
        "sharedram": info.sharedram,
        "bufferram": info.bufferram,
        "totalswap": info.totalswap,
        "freeswap": info.freeswap,
        "procs": info.procs,
        "totalhigh": info.totalhigh,
        "freehigh": info.freehigh,
        "mem_unit": info.mem_unit,
    });

    #[allow(clippy::disallowed_methods)]
    let info = serde_json::to_string_pretty(&info).unwrap();
    println!("{info}");

    Ok(ExitCode::SUCCESS)
}

fn help() {
    println!("Usage: syd-info [-h]");
    println!("Print system information.");
}
