yggdrasil/src/config.rs

96 lines
3.0 KiB
Rust

/*
* Yggdrasil: Minecraft authentication server
* Copyright (C) 2023 0xf8.dev@proton.me
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use std::fs;
use std::path::PathBuf;
use std::str::FromStr;
use anyhow::Result;
use ftlog::{debug, error, info, log, trace, warn};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
#[serde(skip)]
pub location: PathBuf,
pub port: i16,
pub address: String,
}
impl Default for Config {
fn default() -> Self {
Self {
location: std::env::current_dir()
.expect("Couldn't get current directory")
.join("yggdrasilrc"),
port: 8081,
address: "0.0.0.0".parse().expect("Couldn't parse string"),
}
}
}
impl Config {
pub fn new(config_file: &PathBuf) -> Result<Self> {
let new = Self {
location: config_file.to_owned(),
..Default::default()
};
fs::write(config_file, toml::to_string_pretty(&new)?)?;
Ok(new)
}
pub fn load() -> Result<Self> {
let config_file = Self::determine_config_file()?;
debug!("Determined config file to be at {}", config_file.display());
if !fs::try_exists(&config_file)? {
return Self::new(&config_file);
}
let data = fs::read_to_string(&config_file)?;
match toml::from_str::<Config>(&data) {
Ok(mut c) => Ok(c.validate(&config_file).to_owned()),
Err(_) => {
let old = config_file.to_str().unwrap().to_string() + ".old";
warn!("Outdated/invalid config file, replacing! (Old config available at {old})");
fs::copy(&config_file, old)?;
let mut c = Self::new(&config_file)?;
Ok(c.validate(&config_file).to_owned())
}
}
}
fn validate(&mut self, config_file: &PathBuf) -> &Self {
debug!("Loaded config: {self:?}");
self.location = config_file.to_owned();
self
}
pub fn save(&self, to: PathBuf) -> Result<()> {
debug!("Saving config to {}", to.display());
Ok(fs::write(to, toml::to_string_pretty(self)?)?)
}
fn determine_config_file() -> Result<PathBuf> {
Ok(match std::env::var("CONFIG") {
Ok(config_dir) => PathBuf::from_str(config_dir.as_str())?,
Err(_) => Self::default().location,
})
}
}