malwaredb 0.3.2

Service for storing malicious, benign, or unknown files and related metadata and relationships.
// SPDX-License-Identifier: Apache-2.0

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 {
    /// Specify a path (or a default path is used)
    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)
    }
}

/// Rename the Malware DB instance
#[derive(Clone, Debug, Args, PartialEq)]
pub struct Rename {
    /// New name for this Malware DB instance
    #[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)
    }
}