use std::fs::{File, OpenOptions};
use std::io;
use std::path::{Path, PathBuf};
use fs2::FileExt;
use super::{PINS_DIR, PinError, checked_name};
const LOCK_SUFFIX: &str = "profile.lock";
#[derive(Debug)]
pub struct ProfileLock {
_file: File,
}
pub fn lock_path(mur_home: &Path, agent: &str) -> PathBuf {
mur_home
.join(PINS_DIR)
.join(format!("{agent}.{LOCK_SUFFIX}"))
}
pub fn lock_profile(
mur_home: &Path,
agent: &str,
on_wait: impl FnOnce(),
) -> Result<ProfileLock, PinError> {
checked_name(agent)?;
let path = lock_path(mur_home, agent);
let io_err = |source: io::Error| PinError::Io {
path: path.clone(),
source,
};
std::fs::create_dir_all(mur_home.join(PINS_DIR)).map_err(io_err)?;
let file = OpenOptions::new()
.create(true)
.read(true)
.write(true)
.truncate(false)
.open(&path)
.map_err(io_err)?;
if file.try_lock_exclusive().is_err() {
on_wait();
file.lock_exclusive().map_err(io_err)?;
}
Ok(ProfileLock { _file: file })
}