1use std::fs;
2use std::path::PathBuf;
3use config::Config;
4use inquire::Text;
5use inquire::validator::StringValidator;
6
7const DEFAULT_CLOUD_ENDPOINT: &str = "https://localtest.rs/entrypoint";
8
9fn default() -> anyhow::Result<PathBuf> {
10    let xdg_dirs = xdg::BaseDirectories::with_prefix("rslocal").unwrap();
11    let cfg_path = xdg_dirs.place_config_file("config.ini")
12        .expect("cannot create configuration directory");
13    Ok(cfg_path)
14}
15
16pub fn load(name: &str) -> anyhow::Result<Config> {
17    let path = default()?;
18    let cfg = Config::builder()
19        .add_source(config::File::with_name(path.to_str().unwrap()))
20        .add_source(config::File::with_name(name).required(false))
21        .build()?;
22    Ok(cfg)
23}
24
25pub fn setup() -> anyhow::Result<()> {
26    let required: StringValidator = &|input| { if input.is_empty() { Err(String::from("value required!")) } else { Ok(()) } };
27    let ep = Text::new("server endpoint?").with_validator(required).prompt()?;
28    let token = Text::new("authorization token?").with_validator(required).prompt()?;
29    let cfg_content = format!("endpoint={}\ntoken={}", ep, token);
30
31    let cfg_path = default()?;
32    fs::write(&cfg_path, cfg_content)?;
33    println!("config saved at {:?}", cfg_path);
34    Ok(())
35}