use std::io::Read as _;
use std::path::Path;
use anyhow::{Context as _, Result};
use zeroize::Zeroizing;
#[cfg(not(unix))]
mod other;
#[cfg(unix)]
mod unix;
#[cfg(not(unix))]
use other as platform;
#[cfg(unix)]
use unix as platform;
pub fn private_folder(dir: &Path, mine: &Path) -> Result<()> {
let folder =
std::fs::symlink_metadata(dir).with_context(|| format!("reading {}", dir.display()))?;
let made =
std::fs::symlink_metadata(mine).with_context(|| format!("reading {}", mine.display()))?;
platform::private_folder(dir, &folder, &made)
}
pub fn read(path: &Path) -> Result<Zeroizing<String>> {
let mut file =
std::fs::File::open(path).with_context(|| format!("reading {}", path.display()))?;
let meta = file
.metadata()
.with_context(|| format!("reading {}", path.display()))?;
let dir = path
.parent()
.map(std::fs::metadata)
.transpose()
.with_context(|| format!("reading the folder of {}", path.display()))?;
platform::check(path, &meta, dir.as_ref(), remake(path))?;
let mut text = Zeroizing::new(String::new());
file.read_to_string(&mut text)
.with_context(|| format!("reading {}", path.display()))?;
Ok(text)
}
pub fn problem(path: &Path) -> Option<String> {
let meta = std::fs::metadata(path).ok()?;
let dir = path.parent().and_then(|d| std::fs::metadata(d).ok());
platform::check(path, &meta, dir.as_ref(), remake(path))
.err()
.map(|e| format!("{e:#}"))
}
fn remake(path: &Path) -> &'static str {
let name = path.file_name().and_then(|n| n.to_str());
if name == Some(crate::audit_key::KEY_FILE) {
"move the audit log aside as evidence and run `openmoat init`, which starts a new log \
with a new key (never remove the key alone)"
} else if name == Some(crate::audit_signing::KEY_FILE) {
"run `openmoat audit checkpoint --new-key` in your terminal, and give the new public key \
`openmoat doctor` shows to whoever checks your checkpoints"
} else {
"make a new one (remove the file; `openmoat proxy ca init` for the CA)"
}
}