use crate::config::{AppConfig, CONFIG_FILE_NAME, Provider};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct StandaloneInstall {
pub config_path: PathBuf,
pub fqdn: String,
pub provider: Provider,
pub syncing: Option<bool>,
}
pub fn default_install_dirs() -> Vec<PathBuf> {
crate::paths::default_data_dir().into_iter().collect()
}
pub fn find_conflicts(fqdns: &[&str]) -> Vec<StandaloneInstall> {
find_conflicts_in(&default_install_dirs(), fqdns)
}
pub fn find_conflicts_in(dirs: &[PathBuf], fqdns: &[&str]) -> Vec<StandaloneInstall> {
let wanted: Vec<String> = fqdns.iter().map(|f| canon(f)).collect();
let mut out = Vec::new();
for dir in dirs {
let path = dir.join(CONFIG_FILE_NAME);
let Ok(cfg) = AppConfig::load(&path) else {
continue;
};
let fqdn = canon(&cfg.record_fqdn());
if wanted.contains(&fqdn) {
out.push(StandaloneInstall {
config_path: path,
syncing: sync_lock_held(&fqdn),
fqdn,
provider: cfg.provider,
});
}
}
out
}
fn canon(s: &str) -> String {
s.trim().trim_end_matches('.').to_ascii_lowercase()
}
fn sync_lock_held(fqdn: &str) -> Option<bool> {
let dir = crate::paths::default_lock_dir().ok()?;
let path = dir.join(format!(
"{}.lock",
crate::lock::sanitize_name(&format!("sync-{fqdn}"))
));
lock_held(&path)
}
fn lock_held(path: &Path) -> Option<bool> {
use fs2::FileExt;
let f = match std::fs::File::open(path) {
Ok(f) => f,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Some(false),
Err(_) => return None,
};
match f.try_lock_shared() {
Ok(()) => {
let _ = FileExt::unlock(&f);
Some(false)
}
Err(_) => Some(true),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lock_detection() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("sync_x.lock");
assert_eq!(lock_held(&p), Some(false));
let held = crate::lock::SingleInstanceLock::acquire_at(&p).unwrap();
assert_eq!(lock_held(&p), Some(true));
drop(held);
assert_eq!(lock_held(&p), Some(false));
}
}