use crate::template::get_default_template;
use std::fs;
pub fn init(template: Option<String>, cfg_path: &str) -> Result<(), String> {
if fs::metadata(cfg_path).is_ok() {
Err(String::from("A Bonnie configuration file already exists in this directory. If you want to create a new one, please delete the old one first."))
} else {
let output;
if matches!(template, Some(_)) && fs::metadata(template.as_ref().unwrap()).is_ok() {
let template_path = template.unwrap();
let contents = fs::read_to_string(&template_path);
let contents = match contents {
Ok(contents) => contents,
Err(_) => return Err(format!("An error occurred while attempting to read the given template file '{}'. Please make sure the file exists and you have the permissions necessary to read from it.", &template_path))
};
output = fs::write(cfg_path, contents);
} else if matches!(template, Some(_)) && fs::metadata(template.as_ref().unwrap()).is_err() {
return Err(format!("The given template file at '{}' does not exist or can't be read. Please make sure the file exists and you have the permissions necessary to read from it.", template.as_ref().unwrap()));
} else {
let template = get_default_template()?;
output = fs::write(cfg_path, template);
}
match output {
Ok(_) => Ok(()),
Err(_) => Err(format!("Error creating new {}, make sure you have the permissions to write to this directory.", cfg_path))
}
}
}