use anyhow::Result;

use std::process::Command;

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct User {
    pub name: String,
    pub uid: u32,
}

pub fn get_users() -> Result<Vec<User>> {
    let raw = Command::new("getent").arg("passwd").output()?;
    let raw = String::from_utf8_lossy(&raw.stdout);
    let users: Vec<User> = raw
        .lines()
        .map(|line| {
            let parts: Vec<&str> = line.split(':').collect();
            User {
                name: parts[0].to_string(),
                uid: parts[2].parse().unwrap(),
            }
        })
        .collect();

    Ok(users)
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Group {
    pub name: String,
    pub gid: u32,
}

pub fn get_groups() -> Result<Vec<Group>> {
    let raw = Command::new("getent").arg("group").output()?;
    let raw = String::from_utf8_lossy(&raw.stdout);
    let groups: Vec<Group> = raw
        .lines()
        .map(|line| {
            let parts: Vec<&str> = line.split(':').collect();
            Group {
                name: parts[0].to_string(),
                gid: parts[2].parse().unwrap(),
            }
        })
        .collect();

    Ok(groups)
}
