use nix::errno::Errno;

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

pub fn clear() -> Result<(), CapsError> {
    for c in super::all() {
        if has_cap(c)? {
            drop(c)?;
        }
    }
    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<super::CapsHashSet, CapsError> {
    let mut res = super::CapsHashSet::default();
    for c in runtime::thread_all_supported() {
        if has_cap(c)? {
            res.insert(c);
        }
    }
    Ok(res)
}
