use nix::errno::Errno;

use crate::caps::{errors::CapsError, nr, Capabilities, Capability};

pub fn clear() -> Result<(), CapsError> {
    #[expect(clippy::disallowed_methods)]
    for flag in Capabilities::all() {
        let cap = flag.try_into().unwrap();

        if has_cap(cap).unwrap_or(false) {
            drop(cap)?;
        }
    }

    Ok(())
}

pub fn drop(cap: Capability) -> Result<(), CapsError> {
    Errno::result(unsafe {
        nix::libc::prctl(
            nr::PR_CAPBSET_DROP,
            nix::libc::c_uint::from(cap.index()),
            0,
            0,
        )
    })
    .map(std::mem::drop)
    .map_err(CapsError)
}

pub fn has_cap(cap: Capability) -> Result<bool, CapsError> {
    let ret = Errno::result(unsafe {
        nix::libc::prctl(
            nr::PR_CAPBSET_READ,
            nix::libc::c_uint::from(cap.index()),
            0,
            0,
        )
    })
    .map_err(CapsError)?;

    match ret {
        0 => Ok(false),
        _ => Ok(true),
    }
}

pub fn read() -> Result<Capabilities, CapsError> {
    let mut res = Capabilities::empty();

    #[expect(clippy::disallowed_methods)]
    for flag in Capabilities::all() {
        let cap = flag.try_into().unwrap();

        if has_cap(cap).unwrap_or(false) {
            res |= flag;
        }
    }

    Ok(res)
}
