use std::path::{Path, PathBuf};
use crate::config::types::io::atomic_write;
use crate::config::{Config, opencrabs_home};
pub const CONFIG_EXAMPLE: &str = include_str!("../../config.toml.example");
pub const KEYS_EXAMPLE: &str = include_str!("../../keys.toml.example");
pub fn config_path() -> PathBuf {
Config::system_config_path().unwrap_or_else(|| opencrabs_home().join("config.toml"))
}
pub fn keys_path() -> PathBuf {
opencrabs_home().join("keys.toml")
}
fn seed_if_absent(path: &Path, contents: &str) -> std::io::Result<bool> {
if path.exists() {
return Ok(false);
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
atomic_write(path, contents)?;
Ok(true)
}
pub fn ensure_config_seeded() -> bool {
let path = config_path();
match seed_if_absent(&path, CONFIG_EXAMPLE) {
Ok(true) => {
tracing::info!("Seeded config.toml from the shipped example at {:?}", path);
true
}
Ok(false) => false,
Err(e) => {
tracing::warn!("Could not seed config.toml at {:?}: {}", path, e);
false
}
}
}
pub fn ensure_keys_seeded() -> bool {
let path = keys_path();
match seed_if_absent(&path, KEYS_EXAMPLE) {
Ok(true) => {
tracing::info!("Seeded keys.toml from the shipped example at {:?}", path);
true
}
Ok(false) => false,
Err(e) => {
tracing::warn!("Could not seed keys.toml at {:?}: {}", path, e);
false
}
}
}
pub fn enable_providers_with_keys(config: &Config) -> Vec<String> {
use crate::utils::providers::{KNOWN_PROVIDERS, config_for};
let mut written = Vec::new();
for meta in KNOWN_PROVIDERS {
if !config_for(&config.providers, meta.id).is_some_and(|c| c.api_key.is_some()) {
continue;
}
match Config::write_key(meta.config_section, "enabled", "true") {
Ok(_) => written.push(meta.config_section.to_string()),
Err(e) => tracing::warn!(
"Could not enable {} in the seeded config: {}",
meta.config_section,
e
),
}
}
written
}