| 1 |
use anyhow::{Context, Result}; |
| 2 |
use serde::{Deserialize, Serialize}; |
| 3 |
use std::fs; |
| 4 |
use std::path::PathBuf; |
| 5 |
|
| 6 |
const DEFAULT_PATH: &str = "/etc/mountaineer/sysop.toml"; |
| 7 |
|
| 8 |
pub fn path() -> PathBuf { |
| 9 |
std::env::var_os("SYSOP_CONFIG") |
| 10 |
.map(PathBuf::from) |
| 11 |
.unwrap_or_else(|| PathBuf::from(DEFAULT_PATH)) |
| 12 |
} |
| 13 |
|
| 14 |
#[derive(Debug, Default, Serialize, Deserialize)] |
| 15 |
pub struct Config { |
| 16 |
#[serde(default)] |
| 17 |
pub motd: Motd, |
| 18 |
} |
| 19 |
|
| 20 |
#[derive(Debug, Serialize, Deserialize)] |
| 21 |
pub struct Motd { |
| 22 |
pub enabled: bool, |
| 23 |
} |
| 24 |
|
| 25 |
impl Default for Motd { |
| 26 |
fn default() -> Self { |
| 27 |
Self { enabled: true } |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
pub fn load() -> Result<Config> { |
| 32 |
let p = path(); |
| 33 |
if !p.exists() { |
| 34 |
return Ok(Config::default()); |
| 35 |
} |
| 36 |
let s = fs::read_to_string(&p).with_context(|| format!("read {}", p.display()))?; |
| 37 |
toml::from_str(&s).with_context(|| format!("parse {}", p.display())) |
| 38 |
} |
| 39 |
|
| 40 |
pub fn save(cfg: &Config) -> Result<()> { |
| 41 |
let p = path(); |
| 42 |
if let Some(dir) = p.parent() { |
| 43 |
fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?; |
| 44 |
} |
| 45 |
let s = toml::to_string_pretty(cfg).context("serialize config")?; |
| 46 |
fs::write(&p, s).with_context(|| format!("write {}", p.display())) |
| 47 |
} |
| 48 |
|