use crate::cli::config::{Config, CONFIG_PATHS};
use std::fs;
use std::path::PathBuf;
use std::process::ExitCode;
use anyhow::{anyhow, ensure};
use clap::Args;
use malwaredb_server::State;
#[derive(Clone, Debug, Args, PartialEq)]
pub struct CreateDefaultConfig {
path: Option<PathBuf>,
}
impl CreateDefaultConfig {
pub fn execute(&self) -> anyhow::Result<ExitCode> {
let config = Config::default();
let config = toml::to_string(&config)?;
let config_path = if let Some(config_path) = &self.path {
config_path.clone()
} else {
#[cfg(target_os = "freebsd")]
let config_path = PathBuf::from(CONFIG_PATHS[1]);
#[cfg(not(target_os = "freebsd"))]
let config_path = PathBuf::from(CONFIG_PATHS[0]);
config_path
};
let config_parent_dir = config_path.parent().unwrap();
fs::create_dir_all(config_parent_dir).unwrap_or_else(|_| {
panic!(
"failed to create parent directory {} for the config file",
config_parent_dir.display()
)
});
ensure!(
!config_path.exists(),
"config file {} already exists! Remove or rename it and try again.",
config_path.display()
);
fs::write(&config_path, config).map_err(|e| {
anyhow!(
"failed to write default config file to {}: {e}",
config_path.display()
)
})?;
Ok(ExitCode::SUCCESS)
}
}
#[derive(Clone, Debug, Args, PartialEq)]
pub struct Rename {
#[arg(long = "name")]
name: String,
}
impl Rename {
pub async fn execute(&self, state: State) -> anyhow::Result<ExitCode> {
state.db_type.set_name(&self.name).await?;
Ok(ExitCode::SUCCESS)
}
}