summaryrefslogtreecommitdiffstats
path: root/ozone-cli/src/main.rs
blob: 4a8f3684d8247f0a7dd6a0e9edcd5277eecca57f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
mod cli;

use std::error::Error;
use std::path::Path;
use std::process::ExitCode;
use log::{error, info, trace, LevelFilter};
use clap::Parser;
use ozone::launcher::{Instance, JavaRuntimeSetting, Launcher, Settings};
use ozone::launcher::version::{VersionList, VersionResult};
use uuid::Uuid;
use ozone::auth::{Account, AuthenticationDatabase};
use crate::cli::{Cli, InstanceCommand, RootCommand};

fn find_account<'a>(auth: &'a AuthenticationDatabase, input: &str) -> Vec<&'a Account> {
    if let Ok(uuid) = input.parse::<Uuid>() {
        todo!()
    }

    let input = input.to_ascii_lowercase();

    auth.users.iter().filter(|a| match *a {
        Account::Dummy(profile) => profile.name.to_ascii_lowercase().starts_with(&input),
        Account::MSA(account) =>
            account.player_profile.as_ref().is_some_and(|p| p.name.to_ascii_lowercase().starts_with(&input)) ||
            account.gamertag.as_ref().is_some_and(|p| p.to_ascii_lowercase().starts_with(&input))
    }).collect()
}

fn display_instance(instance: &Instance, id: Uuid, home: impl AsRef<Path>, selected: bool, verbose: bool) {
    println!("Instance `{}':{}", instance.name, if selected { " (selected)" } else { "" });
    println!("  UUID: {}", id);
    println!("  Version: {}", instance.game_version);
    println!("  Location: {}", home.as_ref().join(Settings::get_instance_path(id)).display());

    if !verbose { return; }

    if let Some(ref args) = instance.jvm_arguments {
        println!("  JVM arguments: <{} argument{}>", args.len(), if args.len() == 1 { "" } else { "s" })
    }

    if let Some(res) = instance.resolution {
        println!("  Resolution: {}x{}", res.width, res.height);
    }

    match &instance.java_runtime {
        Some(JavaRuntimeSetting::Component(c)) => println!("  Java runtime component: {c}"),
        Some(JavaRuntimeSetting::Path(p)) => println!("  Java runtime path: {}", p.display()),
        _ => ()
    }
}

async fn main_inner(cli: Cli) -> Result<ExitCode, Box<dyn Error>> {
    let Some(home) = cli.home.or_else(Launcher::sensible_home) else {
        error!("Could not choose a launcher home directory. Please choose one with `--home'.");
        return Ok(ExitCode::FAILURE); // we print our own error message
    };

    trace!("Sensible home could be {home:?}");
    let mut settings = Settings::load(home.join("ozone.json")).await?;

    match &cli.subcmd {
        RootCommand::Instance(p) => match p.command() {
            InstanceCommand::List => {
                let mut first = true;

                if settings.instances.is_empty() {
                    eprintln!("There are no instances. Create one with `profile create <name>'.");
                    return Ok(ExitCode::SUCCESS);
                }

                for (cur_id, instance) in settings.instances.iter() {
                    if !first {
                        println!();
                    }

                    first = false;

                    let cur_id = *cur_id;
                    let sel = settings.selected_instance.is_some_and(|id| id == cur_id);
                    display_instance(instance, cur_id, &home, sel, false);
                }
            },
            InstanceCommand::Create(args) => {
                if args.name.is_empty() {
                    eprintln!("The instance must not have an empty name.");
                    return Ok(ExitCode::FAILURE);
                }

                let mut inst = if args.clone {
                    if let Some(selected_inst) = settings.get_selected_instance() {
                        let mut inst = selected_inst.clone();
                        inst.name.replace_range(.., &args.name);
                        inst
                    } else {
                        eprintln!("You do not have an instance selected.");
                        return Ok(ExitCode::FAILURE);
                    }
                } else {
                    Instance::new(&args.name)
                };

                if let Some(ref ver_name) = args.settings.version {
                    // FIXME: don't hardcode "versions" path
                    let versions = VersionList::new(home.join("versions"), !cli.offline).await?;
                    if matches!(versions.get_version_lazy(ver_name), VersionResult::None) {
                        eprintln!("The version `{}' could not be found.", ver_name);
                        return Ok(ExitCode::FAILURE);
                    }
                }
                
                args.settings.apply_to(&mut inst);

                let new_id = Uuid::new_v4();
                settings.instances.insert(new_id, inst);
                
                if !args.no_select {
                    settings.selected_instance = Some(new_id);
                }

                settings.save().await?;
            },
            InstanceCommand::Select(args) => {
                if let Ok(uuid) = args.instance.parse::<Uuid>() {
                    if !settings.instances.contains_key(&uuid) {
                        eprintln!("No instances were found by that UUID.");
                        return Ok(ExitCode::FAILURE);
                    }

                    settings.selected_instance = Some(uuid);
                    settings.save().await?;

                    return Ok(ExitCode::SUCCESS);
                }

                let search_norm = args.instance.to_lowercase();

                let found: Vec<_> = settings.instances.iter()
                    .filter(|(_, inst)| {
                        // FIXME: find a better way of doing this matching
                        inst.name.to_lowercase().starts_with(&search_norm)
                    }).collect();

                if found.is_empty() {
                    eprintln!("No instances were found.");
                    return Ok(ExitCode::FAILURE);
                }

                if found.len() > 1 {
                    eprintln!("Ambiguous argument. Found {} instances:", found.len());
                    for (id, inst) in found {
                        eprintln!("- {} ({id})", inst.name);
                    }

                    return Ok(ExitCode::FAILURE);
                }

                let (found_id, found_inst) = found.first().unwrap();
                println!("Selected instance {} ({found_id}).", found_inst.name);

                settings.selected_instance = Some(**found_id);
                settings.save().await?;
            },
            InstanceCommand::Set(args) => {
                let Some(inst) = settings.get_selected_instance_mut() else {
                    eprintln!("No instance selected.");
                    return Ok(ExitCode::FAILURE);
                };

                args.apply_to(inst);
                settings.save().await?;
            },
            InstanceCommand::Delete => {
                let Some(inst) = settings.selected_instance else {
                    eprintln!("No instance selected.");
                    return Ok(ExitCode::FAILURE);
                };

                settings.instances.remove(&inst);
                settings.selected_instance = None;
                settings.save().await?;
            },
            InstanceCommand::Info => {
                let Some(inst) = settings.get_selected_instance() else {
                    eprintln!("No instance selected.");
                    return Ok(ExitCode::FAILURE);
                };
                
                display_instance(inst, settings.selected_instance.unwrap(), &home, false, true);
            },
            InstanceCommand::Rename { name } => {
                if name.is_empty() {
                    eprintln!("The instance must not have an empty name.");
                    return Ok(ExitCode::FAILURE);
                }

                let Some(inst) = settings.get_selected_instance_mut() else {
                    eprintln!("No instance selected.");
                    return Ok(ExitCode::FAILURE);
                };

                inst.name.replace_range(.., name);
                settings.save().await?;
            }
        },
        RootCommand::Launch => {
            let Some(selection) = settings.selected_instance else {
                eprintln!("No instance selected.");
                return Ok(ExitCode::FAILURE);
            };
            
            let inst = settings.instances.get(&selection).expect("settings inconsistency");

            settings.save().await?;

            let launcher = Launcher::new(&home, !cli.offline).await?;

            let launch = launcher.prepare_launch(inst, Settings::get_instance_path(selection), settings.client_id).await.map_err(|e| {
                error!("error launching: {e}");
                e
            })?;

            dbg!(&launch);
            info!("ok");

            ozone::launcher::run_the_game(&launch)?;
        }
        _ => todo!()
    }

    Ok(ExitCode::SUCCESS)
}

#[tokio::main]
async fn main() -> ExitCode {
    // use Warn as the default level to minimize noise on the command line
    simple_logger::SimpleLogger::new().with_level(LevelFilter::Warn).env().init().unwrap();

    let arg = Cli::parse();

    main_inner(arg).await.unwrap_or_else(|e| {
        error!("Launcher initialization error:");
        error!("{e}");

        ExitCode::FAILURE
    })
}