use std::{fs::File, path::Path, io::{Error, ErrorKind}};
use crate::{config::Cfg, db::{db_setup, s_config_get_version, s_config_create_version, s_insert_column, lists_get_all_ids, lists_get, userlist_get_all_current_version_ids, s_userlist_update_download, s_config_update_version}, modrinth::get_raw_versions};
pub async fn setup(config: Cfg) -> Result<(), Box<dyn std::error::Error>> {
let db_file = format!("{}/data.db", String::from(&config.data));
if !Path::new(&db_file).exists() {
return create(config, db_file);
}
match s_config_get_version(config.clone()) {
Ok(ver) => {
match ver.as_str() {
"0.2" => to_03(config)?,
"0.3" => to_04(config)?,
_ => return Err(Box::new(Error::new(ErrorKind::Other, "UNKNOWN_VERSION")))
}
},
Err(..) => to_02(config).await?
};
Ok(())
}
fn create(config: Cfg, db_file: String) -> Result<(), Box<dyn std::error::Error>> {
File::create(db_file)?;
db_setup(config)?;
Ok(())
}
async fn to_02(config: Cfg) -> Result<(), Box<dyn std::error::Error>> {
let lists = lists_get_all_ids(config.clone())?;
for list in lists {
println!("Updating {}", list);
s_insert_column(config.clone(), String::from(&list), String::from("current_download"), String::from("TEXT"), None)?;
let full_list = lists_get(config.clone(), String::from(&list))?;
let versions = userlist_get_all_current_version_ids(config.clone(), full_list.clone().id)?;
let raw_versions = get_raw_versions(String::from(&config.apis.modrinth), versions).await;
for ver in raw_versions {
println!("Adding link for {}", ver.project_id);
let file = ver.files.into_iter().find(|f| f.primary).unwrap();
s_userlist_update_download(config.clone(), String::from(&full_list.id), ver.project_id, file.url)?;
}
};
s_config_create_version(config)?;
Ok(())
}
fn to_03(config: Cfg) -> Result<(), Box<dyn std::error::Error>> {
s_insert_column(config.clone(), String::from("lists"), String::from("download_folder"), String::from("TEXT"), None)?;
s_config_update_version(config, String::from("0.3"))
}
fn to_04(config: Cfg) -> Result<(), Box<dyn std::error::Error>> {
for list_id in lists_get_all_ids(config.clone())? {
s_insert_column(config.clone(), list_id, String::from("disabled_versions"), String::from("TEXT"), Some(String::from("NONE")))?;
}
s_config_update_version(config, String::from("0.4"))
}