use std::path::PathBuf;
use anyhow::Result;
use openmoat_core::Policy;
use openmoat_hosts::Host;
use super::backend::{Input, Output, SandboxBackend};
use super::{install, lower_for_hosts, proxy_port, with_read_roots};
use crate::home::Home;
const LINUX: bool = cfg!(target_os = "linux");
#[derive(Debug)]
pub struct Plan {
pub default_read_roots: bool,
pub proxy_port: Option<u16>,
pub serve_without_credential: bool,
outputs: Vec<(Host, Box<dyn Output>)>,
}
type Sandbox = (Host, &'static dyn SandboxBackend, PathBuf);
impl Plan {
pub fn new(home: &Home, policy: &Policy) -> Result<Self> {
let binary = crate::install::self_paths::recorded_binary(home)?;
Self::for_binary(home, policy, &binary)
}
pub fn for_binary(state: &Home, policy: &Policy, binary: &std::path::Path) -> Result<Self> {
let binary_paths = crate::install::self_paths::sandbox_paths(binary);
let mut policy = policy.clone();
crate::install::self_paths::protect(&mut policy, &binary_paths);
let (policy, default_read_roots) = with_read_roots(&policy)?;
let (home, real_home) = crate::context::home_spellings()?;
let homes: Vec<String> = std::iter::once(home.clone())
.chain(real_home.clone())
.collect();
let ir = lower_for_hosts(
&policy,
&home,
real_home,
crate::context::moved_dirs(state)?,
crate::context::CASE_INSENSITIVE_PATHS,
)?;
let mut sandboxes = Vec::new();
for host in install::hosts() {
if let Some(backend) = install::backend(host) {
sandboxes.push((host, backend, install::settings_path(state, host)?));
}
}
let proxy_port = proxy_port(&policy);
let input = Input {
ir: &ir,
proxy_port,
homes: &homes,
binary_paths: &binary_paths,
linux: LINUX,
};
Ok(Self {
default_read_roots,
proxy_port,
serve_without_credential: policy
.sandbox
.as_ref()
.is_some_and(|s| s.proxy_serve_without_credential),
outputs: generate(&input, sandboxes)?,
})
}
pub fn output(&self, host: Host) -> Option<&dyn Output> {
self.outputs
.iter()
.find(|(h, _)| *h == host)
.map(|(_, output)| output.as_ref())
}
pub fn writable_dirs(&self) -> Vec<String> {
self.outputs
.iter()
.flat_map(|(_, output)| output.writable_dirs())
.collect()
}
}
fn generate(
input: &Input<'_>,
sandboxes: impl IntoIterator<Item = Sandbox>,
) -> Result<Vec<(Host, Box<dyn Output>)>> {
sandboxes
.into_iter()
.map(|(host, backend, settings)| Ok((host, backend.generate(input, &settings)?)))
.collect()
}
#[cfg(test)]
mod tests;