//
// Syd: rock-solid application kernel
// src/uts.rs: Interface to uname(2)
//
// Copyright (c) 2025 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

// SAFETY: This module has (almost) been liberated from unsafe code!
// UtsName::as_bytes() uses std::slice::from_raw_parts which is unsafe.
// Use deny rather than forbid so we can allow this case.
#![deny(unsafe_code)]

use std::fmt;

use serde::{ser::SerializeMap, Serialize, Serializer};

use crate::path::XPath;

// Length of the entries in `struct utsname' is 65.
pub(crate) const UTSNAME_LEN: usize = 65;

/// C-compatible layout of the `utsname` structure.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[repr(C)]
pub struct UtsName {
    // Name of the operating system implementation.
    pub(crate) sysname: [u8; UTSNAME_LEN],
    // Network name of this machine.
    pub(crate) nodename: [u8; UTSNAME_LEN],
    // Release level of the operating system.
    pub(crate) release: [u8; UTSNAME_LEN],
    // Version level of the operating system.
    pub(crate) version: [u8; UTSNAME_LEN],
    // Machine hardware platform.
    pub(crate) machine: [u8; UTSNAME_LEN],
    // NIS or YP domain name of this machine.
    pub(crate) domainname: [u8; UTSNAME_LEN],
}

impl Default for UtsName {
    fn default() -> Self {
        Self {
            sysname: [0u8; UTSNAME_LEN],
            nodename: [0u8; UTSNAME_LEN],
            release: [0u8; UTSNAME_LEN],
            version: [0u8; UTSNAME_LEN],
            machine: [0u8; UTSNAME_LEN],
            domainname: [0u8; UTSNAME_LEN],
        }
    }
}

impl UtsName {
    /// Return a byte-wise view of the UtsName structure.
    pub fn as_bytes(&self) -> &[u8] {
        // SAFETY: UtsName is repr(C) and contains only [u8; N] fields.
        #[expect(unsafe_code)]
        unsafe {
            std::slice::from_raw_parts(self as *const Self as *const u8, size_of::<Self>())
        }
    }

    /// Return name of the operating system implementation.
    pub fn sysname(&self) -> &XPath {
        XPath::from_bytes_until_nul(&self.sysname)
    }

    /// Return network name of this machine.
    pub fn nodename(&self) -> &XPath {
        XPath::from_bytes_until_nul(&self.nodename)
    }

    /// Return release level of the operating system.
    pub fn release(&self) -> &XPath {
        XPath::from_bytes_until_nul(&self.release)
    }

    /// Return version level of the operating system.
    pub fn version(&self) -> &XPath {
        XPath::from_bytes_until_nul(&self.version)
    }

    /// Return machine hardware platform.
    pub fn machine(&self) -> &XPath {
        XPath::from_bytes_until_nul(&self.machine)
    }

    /// Return NIS or YP domain name of this machine.
    pub fn domainname(&self) -> &XPath {
        XPath::from_bytes_until_nul(&self.domainname)
    }
}

impl fmt::Display for UtsName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "{} version {} {}",
            self.sysname(),
            self.release(),
            self.version()
        )
    }
}

impl Serialize for UtsName {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(Some(6))?;
        map.serialize_entry("sysname", self.sysname())?;
        map.serialize_entry("nodename", self.nodename())?;
        map.serialize_entry("release", self.release())?;
        map.serialize_entry("version", self.version())?;
        map.serialize_entry("machine", self.machine())?;
        map.serialize_entry("domainname", self.domainname())?;
        map.end()
    }
}
