use std::path::{Path, PathBuf};
use zakura_chain::{common::default_cache_dir, parameters::Network};
const DEFAULT_NETWORK_IDENTITY_DIR: &str = ".zakura";
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum CacheDir {
IsEnabled(bool),
CustomPath(PathBuf),
}
impl From<bool> for CacheDir {
fn from(value: bool) -> Self {
CacheDir::IsEnabled(value)
}
}
impl From<PathBuf> for CacheDir {
fn from(value: PathBuf) -> Self {
CacheDir::CustomPath(value)
}
}
impl CacheDir {
pub fn default_path() -> Self {
Self::IsEnabled(true)
}
pub fn disabled() -> Self {
Self::IsEnabled(false)
}
pub fn custom_path(path: impl AsRef<Path>) -> Self {
Self::CustomPath(path.as_ref().to_owned())
}
pub fn is_enabled(&self) -> bool {
match self {
CacheDir::IsEnabled(is_enabled) => *is_enabled,
CacheDir::CustomPath(_) => true,
}
}
pub fn peer_cache_file_path(&self, network: &Network) -> Option<PathBuf> {
Some(
self.cache_dir()?
.join("network")
.join(format!("{}.peers", network.lowercase_name())),
)
}
pub fn zakura_node_secret_key_file_path(&self, network: &Network) -> PathBuf {
zakura_node_secret_key_file_path(&default_network_identity_dir(), network)
}
pub fn cache_dir(&self) -> Option<PathBuf> {
match self {
Self::IsEnabled(is_enabled) => is_enabled.then(default_cache_dir),
Self::CustomPath(cache_dir) => Some(cache_dir.to_owned()),
}
}
}
impl Default for CacheDir {
fn default() -> Self {
Self::default_path()
}
}
pub(crate) fn default_network_identity_dir() -> PathBuf {
dirs::home_dir()
.unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
.join(DEFAULT_NETWORK_IDENTITY_DIR)
}
pub(crate) fn zakura_node_secret_key_file_path(identity_dir: &Path, network: &Network) -> PathBuf {
identity_dir.join(format!(
"{}.zakura-iroh-secret-key",
network.lowercase_name()
))
}