use openmoat_hosts::Host;
use super::{Attention, Mark, Row};
use crate::protection::{Level, Protection, Required};
use crate::sandbox::install as host_sandbox;
#[derive(Debug, Default)]
pub struct AgentTable {
pub rows: Vec<Row>,
pub not_installed: Vec<&'static str>,
}
pub fn agent_table(agents: &[Protection], attention: &Attention, verbose: bool) -> AgentTable {
let mut table = AgentTable::default();
for agent in agents {
let host = Host::ALL.into_iter().find(|h| h.id() == agent.host);
let (mark, text) = match agent.level {
Level::NotFound => {
table.not_installed.push(agent.name);
continue;
}
Level::NotSetUp => {
let text = format!("not set up (openmoat init --hosts {})", agent.host);
(Mark::Info, text)
}
Level::NotProtected => (Mark::Broken, with_reason(agent, true)),
Level::HookOnly => {
let expected = host.is_none_or(expected_hook_only);
let mark = if expected { Mark::Ok } else { Mark::Attention };
let no_sandbox = host.is_none_or(|h| host_sandbox::format(h).is_none());
(mark, with_reason(agent, verbose || !no_sandbox))
}
Level::HookAndOsSandbox => (Mark::Ok, with_reason(agent, true)),
};
let mark = if mark == Mark::Ok && attention.names(agent.name) {
Mark::Attention
} else {
mark
};
let below = agent.required.as_ref().filter(|r| !r.met);
let mark = if below.is_some() { Mark::Broken } else { mark };
let through = host
.filter(|_| agent.level.hooked())
.and_then(crate::install::host_version::hook_api);
let text = match through {
Some(through) => format!("{text} · {through}"),
None => text,
};
table.rows.push(Row::new(mark, agent.name, text));
if let Some(required) = &agent.required {
table.rows.push(required_row(agent.name, required));
}
if let Some(limit) = agent.limit.filter(|_| agent.level.hooked()) {
table.rows.push(Row::new(
Mark::Attention,
agent.name,
format!("limit: {limit}"),
));
}
}
table
}
pub fn os_sandbox_rows(agents: &[Protection]) -> Vec<Row> {
agents
.iter()
.filter_map(|agent| {
let sandbox = agent.os_sandbox.as_ref()?;
Some(Row::new(Mark::Info, agent.name, sandbox.line()))
})
.collect()
}
pub fn fails_open_rows(agents: &[Protection]) -> Vec<Row> {
agents
.iter()
.filter_map(|agent| {
let line = agent.hook_failure.as_ref()?.line()?;
Some(Row::new(Mark::Info, agent.name, line))
})
.collect()
}
fn required_row(name: &str, required: &Required) -> Row {
let head = format!("required: {} ({})", required.label(), required.by);
match (&required.missing, &required.fix) {
(Some(missing), Some(fix)) => Row::new(
Mark::Broken,
name,
format!("{head}, not met, so every call is denied: {missing}; to meet it, {fix}"),
),
_ => Row::new(Mark::Ok, name, format!("{head}, met")),
}
}
fn expected_hook_only(host: Host) -> bool {
host_sandbox::format(host).is_none() || host_sandbox::unavailable(host).is_some()
}
fn with_reason(agent: &Protection, reason: bool) -> String {
match agent.reason.as_deref().filter(|_| reason) {
Some(why) => format!("{} ({why})", agent.level.label()),
None => agent.level.label().to_owned(),
}
}