use crate::db::save_path::SavePath;
use crate::db::tracker_url::TrackerUrl;
use argh::FromArgs;
use core::panic;
use directories::BaseDirs;
use std::path::{Path, PathBuf, MAIN_SEPARATOR};
fn get_qb_dir() -> PathBuf {
let base_dirs = BaseDirs::new().unwrap();
base_dirs.data_local_dir().join("qBittorrent")
}
#[derive(Debug, FromArgs)]
struct CLIOpts {
#[argh(option, short = 'p')]
config_dir: Option<String>,
#[argh(switch, short = 'd')]
disable_backup: bool,
#[argh(switch, short = 'v')]
verbose: bool,
#[argh(option)]
old_path: Option<String>,
#[argh(option)]
new_path: Option<String>,
#[argh(switch)]
use_unix_sep: bool,
#[argh(switch)]
use_win_sep: bool,
#[argh(option)]
old_tracker: Option<String>,
#[argh(option)]
new_tracker: Option<String>,
#[argh(switch)]
db_to_fastresume: bool,
#[argh(option, short = 'o')]
output_dir: Option<String>,
}
#[derive(Debug)]
pub struct Config {
pub qb_directory: PathBuf,
pub db_file: PathBuf,
pub disable_backup: bool,
pub save_path: Option<SavePath>,
pub tracker_url: Option<TrackerUrl>,
pub db_to_fastresume: bool,
pub output_directory: Option<String>,
pub verbose: bool,
}
impl Config {
pub fn build() -> Result<Config, String> {
let args: CLIOpts = argh::from_env();
let qb_dir = get_qb_dir();
let qb_directory = match args.config_dir {
Some(dir) => PathBuf::from(&dir),
_ => qb_dir,
};
let db_file = Path::new(&qb_directory).join("torrents.db");
let save_path = match (args.old_path, args.new_path) {
(Some(old), Some(new)) => {
let separator: String;
if args.use_unix_sep {
separator = '/'.to_string();
} else if args.use_win_sep {
separator = '\\'.to_string();
} else {
separator = MAIN_SEPARATOR.to_string();
}
let old_unix = old.replace('\\', "/");
let new_unix = new.replace('\\', "/");
Some(SavePath {
old_unix,
new_unix,
old,
new,
separator,
})
}
(None, None) => None,
(Some(_old), None) => panic!("--new-path is missing!"),
(None, Some(_new)) => panic!("--old-path is missing!"),
};
let tracker_url = match (args.old_tracker, args.new_tracker) {
(Some(old), Some(new)) => Some(TrackerUrl { old, new }),
(None, None) => None,
(Some(_old), None) => panic!("--new-tracker is missing!"),
(None, Some(_new)) => panic!("--old-tracker is missing!"),
};
let config = Config {
qb_directory,
db_file,
disable_backup: args.disable_backup,
save_path,
tracker_url,
db_to_fastresume: args.db_to_fastresume,
output_directory: args.output_dir,
verbose: args.verbose,
};
if config.verbose {
println!("Verbose output enabled");
println!("Using {:?} as qB directory", config.qb_directory.display());
println!("Using {:?} as qB database", config.db_file.display());
println!("Save path: {:?}", config.save_path);
println!("Tracker url: {:?}", config.tracker_url);
}
Ok(config)
}
}