use std::{fs::create_dir_all, path::PathBuf};
const DEFAULT_CONFIG_DIR: &str = "/usr/share/signstar/";
const ETC_OVERRIDE_CONFIG_DIR: &str = "/etc/signstar/";
const RUN_OVERRIDE_CONFIG_DIR: &str = "/run/signstar/";
const USR_LOCAL_OVERRIDE_CONFIG_DIR: &str = "/usr/local/share/signstar/";
const CONFIG_FILE: &str = "config.toml";
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Unable to create directory {dir}:\n{source}")]
CreateDirectory { dir: String, source: std::io::Error },
}
pub fn get_config_file() -> Option<PathBuf> {
[
get_etc_override_config_file_path(),
get_run_override_config_file_path(),
get_usr_local_override_config_file_path(),
get_default_config_file_path(),
]
.into_iter()
.find(|file| file.is_file())
}
pub fn get_config_file_or_default() -> PathBuf {
let Some(config) = get_config_file() else {
return get_default_config_file_path();
};
config
}
pub fn get_config_file_paths() -> Vec<PathBuf> {
vec![
get_etc_override_config_file_path(),
get_run_override_config_file_path(),
get_usr_local_override_config_file_path(),
get_default_config_file_path(),
]
}
pub fn get_etc_override_config_file_path() -> PathBuf {
PathBuf::from([ETC_OVERRIDE_CONFIG_DIR, CONFIG_FILE].concat())
}
pub fn get_etc_override_dir_path() -> PathBuf {
PathBuf::from(ETC_OVERRIDE_CONFIG_DIR)
}
pub fn get_run_override_config_file_path() -> PathBuf {
PathBuf::from([RUN_OVERRIDE_CONFIG_DIR, CONFIG_FILE].concat())
}
pub fn get_run_override_dir_path() -> PathBuf {
PathBuf::from(RUN_OVERRIDE_CONFIG_DIR)
}
pub fn get_usr_local_override_config_file_path() -> PathBuf {
PathBuf::from([USR_LOCAL_OVERRIDE_CONFIG_DIR, CONFIG_FILE].concat())
}
pub fn get_usr_local_override_dir_path() -> PathBuf {
PathBuf::from(USR_LOCAL_OVERRIDE_CONFIG_DIR)
}
pub fn get_default_config_file_path() -> PathBuf {
PathBuf::from([DEFAULT_CONFIG_DIR, CONFIG_FILE].concat())
}
pub fn get_default_config_dir_path() -> PathBuf {
PathBuf::from(DEFAULT_CONFIG_DIR)
}
pub fn create_default_config_dir() -> Result<(), Error> {
create_dir_all(get_default_config_dir_path()).map_err(|source| Error::CreateDirectory {
dir: DEFAULT_CONFIG_DIR.to_string(),
source,
})
}
pub fn create_etc_override_config_dir() -> Result<(), Error> {
create_dir_all(get_etc_override_dir_path()).map_err(|source| Error::CreateDirectory {
dir: ETC_OVERRIDE_CONFIG_DIR.to_string(),
source,
})
}
pub fn create_run_override_config_dir() -> Result<(), Error> {
create_dir_all(get_run_override_dir_path()).map_err(|source| Error::CreateDirectory {
dir: RUN_OVERRIDE_CONFIG_DIR.to_string(),
source,
})
}
pub fn create_usr_local_override_config_dir() -> Result<(), Error> {
create_dir_all(get_usr_local_override_dir_path()).map_err(|source| Error::CreateDirectory {
dir: USR_LOCAL_OVERRIDE_CONFIG_DIR.to_string(),
source,
})
}