rebos 3.5.2

NixOS-like repeatability for any Linux distro.
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// Source files to include.
mod library; // Full of functions.
mod convert; // Convert one type to another type.
mod places; // Where is stuff stored?
mod cli; // For argument parsing and command structuring.
mod generation; // The generations system.
mod config; // Configuration stuff.
mod obj_print; // Print objects.
mod obj_print_boilerplate; // Boilerplate code for obj print.
mod management; // Stuff related to item management.
mod system; // Used for getting system information.
mod hook; // Hook stuff.
mod lock; // Locking file functionality.
mod proc; // Process management stuff for Rebos.

// Import stuff from source files and crates.
use clap::Parser;
use std::io::{ self, Write };
use library::*;
use config::ConfigSide;
use colored::Colorize;
use piglog::prelude::*;
use piglog::*;
use fspp::*;

// The exit code for the program.
#[derive(PartialEq)]
enum ExitCode {
    Success,
    Fail,
}

// Use this function for testing code!
fn test_code() {
}

// Cleanup when Rebos fails.
fn error_cleanup() {
    let lock_state = match lock::lock_state() {
        Ok(o) => o,
        Err(_) => return,
    };
    if lock_state == lock::LockState::OnOwned {
        let _ = lock::lock_off(); // We don't have to handle this, since this is just
                                  // cleanup and the exit code will be failure anyway.
    }
}

// We are using main() to run another function, and exit according to the exit code.
fn main() -> std::process::ExitCode {
    match app() {
        ExitCode::Success => std::process::ExitCode::SUCCESS,
        ExitCode::Fail => {
            error_cleanup();

            std::process::ExitCode::FAILURE
        },
    }
}

// The "main" function.
fn app() -> ExitCode {
    // Rebos uses unique Rebos process IDs to prevent locking itself when locking other processes.
    proc::init_proc_id();

    test_code(); // This function is for nothing but testing code whilst developing!

    match is_root_user() {
        true => {
            error!("Cannot run as root! Please run as the normal user!");
            return ExitCode::Fail;
        },

        false => {},
    };

    // Migration for legacy directory location! ($HOME/.rebos-base -> $XDG_STATE_HOME/rebos)
    if places::base_legacy().exists() {
        warning!("Detected Rebos base at legacy location, moving it to new location...");
        generic!("'{}' -> '{}'", places::base_legacy().to_string(), places::base().to_string());

        if places::base().exists() {
            match fs_action::delete(&places::base()) {
                Ok(_) => (),
                Err(e) => {
                    fatal!("Failed to delete directory: '{}'", places::base().to_string());
                    println!("{e:#?}");

                    return ExitCode::Fail;
                },
            };
        }

        match fs_action::mv(&places::base_legacy(), &places::base()) {
            Ok(_) => (),
            Err(e) => {
                fatal!("Failed to move directory ('{}') to new location: '{}'", places::base_legacy().to_string(), places::base().to_string());
                println!("{e:#?}");

                return ExitCode::Fail;
            },
        };

        success!("Moved Rebos base directory to new location!");
    }

    let args = cli::Cli::parse();

    match &args.command {
        cli::Commands::Setup => (),
        _ => {
            if places::base().exists() == false {
                error!("It seems that the program is not set up!");
                return ExitCode::Fail;
            }
        },
    }

    #[allow(unreachable_patterns)]
    match &args.command {
        cli::Commands::Gen { command } => {
            match lock::lock_on() {
                Ok(_) => (),
                Err(_) => return ExitCode::Fail,
            };

            match command {
                cli::GenCommands::Commit(c) => {
                    info!("Committing user generation...");

                    match generation::commit(c.msg.as_str()) {
                        Ok(_) => success!("Committed generation successfully! (\"{}\")", c.msg),
                        Err(_) => return ExitCode::Fail,
                    };
                },
                cli::GenCommands::List => {
                    match generation::list_print() {
                        Ok(_) => (),
                        Err(_) => return ExitCode::Fail,
                    };
                },
                cli::GenCommands::CleanDups => {
                    match generation::management::clean_dups(true) {
                        Ok(o) => success!("Deleted {o} generations!"),
                        Err(_) => return ExitCode::Fail,
                    };
                },
                cli::GenCommands::Align => {
                    match generation::management::align(true) {
                        Ok(o) => success!("Aligned {o} generations!"),
                        Err(_) => return ExitCode::Fail,
                    };
                },
                cli::GenCommands::TidyUp => {
                    match generation::management::tidy_up() {
                        Ok(_) => (),
                        Err(_) => return ExitCode::Fail,
                    };
                },
                cli::GenCommands::Info => {
                    let generation = match generation::gen(ConfigSide::User) {
                        Ok(o) => o,
                        Err(_) => return ExitCode::Fail,
                    };

                    obj_print::generation(&generation);
                },
                cli::GenCommands::Latest => {
                    info!("Latest generation number is: {}", match generation::latest_number() {
                        Ok(o) => o,
                        Err(_) => return ExitCode::Fail,
                    });
                },
                cli::GenCommands::DeleteOld(h) => {
                    info!("Deleting old generations...");

                    match generation::delete_old(h.how_many, true) {
                        Ok(_) => success!("Successfully deleted {} generations!", h.how_many),
                        Err(_) => return ExitCode::Fail,
                    };
                },
                cli::GenCommands::Delete(g) => {
                    match generation::delete(g.generation, true) {
                        Ok(_) => (), // Handled by delete().
                        Err(_) => return ExitCode::Fail,
                    };
                },
                cli::GenCommands::Diff { old, new } => {
                    if generation::gen_exists(*old) == false || generation::gen_exists(*new) == false {
                        fatal!("Generation not found!");

                        return ExitCode::Fail;
                    }

                    let gen_1 = generation::get_gen_from_usize(*old).unwrap();
                    let gen_2 = generation::get_gen_from_usize(*new).unwrap();

                    let commit_1 = generation::get_gen_commit_from_usize(*old).unwrap();
                    let commit_2 = generation::get_gen_commit_from_usize(*new).unwrap();

                    let history = library::history_gen(&gen_1, &gen_2);

                    println!(
                        "\n{} {} {}",
                        commit_1.bright_cyan().bold(),
                        "->".bright_black().bold(),
                        commit_2.bright_cyan().bold()
                    );

                    println!("");

                    library::print_history_gen(&history);
                },
                cli::GenCommands::Current { command } => {
                    match command {
                        cli::CurrentCommands::Build => {
                            info!("Building 'current' generation...");

                            match generation::build() {
                                Ok(_) => success!("Built generation successfully!"),
                                Err(_) => return ExitCode::Fail,
                            };
                        },
                        cli::CurrentCommands::Rollback(r) => {
                            info!("Rolling back by {} generations...", r.by);

                            match generation::rollback(r.by, true) {
                                Ok(_) => success!("Rolled back successfully!"),
                                Err(_) => return ExitCode::Fail,
                            };
                        },
                        cli::CurrentCommands::ToLatest => {
                            info!("Jumping to latest generation...");

                            match generation::latest(true) {
                                Ok(_) => success!("Jumped to latest successfully!"),
                                Err(_) => return ExitCode::Fail,
                            };
                        },
                        cli::CurrentCommands::Set(s) => {
                            info!("Jumping to generation {}...", s.to);

                            match generation::set_current(s.to, true) {
                                Ok(_) => success!("Jumped to generation {} successfully!", s.to),
                                Err(_) => return ExitCode::Fail,
                            };
                        },
                        _ => {
                            error!("Command not usable yet!");
                            return ExitCode::Fail;
                        },
                    };
                },
                _ => {
                    error!("Command not usable yet!");
                    return ExitCode::Fail;
                },
            };

            match lock::lock_off() {
                Ok(_) => (),
                Err(_) => return ExitCode::Fail,
            };
        },
        cli::Commands::Setup => {
            info!("Beginning setup...");

            match setup() {
                Ok(_) => success!("Set up the program successfully!"),
                Err(_) => return ExitCode::Fail,
            };
        },
        cli::Commands::Config { command } => {
            match command {
                cli::ConfigCommands::Init => {
                    info!("Creating user configuration...");

                    match config::init_user_config() {
                        Ok(_) => success!("Created user configuration successfully!"),
                        Err(_) => return ExitCode::Fail,
                    };
                },
                cli::ConfigCommands::Check => {
                    let result = match config::check_config() {
                        Ok(o) => o,
                        Err(_) => return ExitCode::Fail,
                    };

                    match result {
                        Ok(misc_info) => config::print_misc_info(&misc_info),
                        Err((e, misc_info)) => {
                            config::print_errors_and_misc_info(&e, &misc_info);

                            return ExitCode::Fail;
                        },
                    };
                },
            };
        },
        cli::Commands::ForceUnlock => {
            if lock::is_lock_on() {
                piglog::warning!("Force unlocking could harm the system if done with the wrong reason!");
                piglog::warning!("You should only force unlock if you know that you ABSOLUTELY need to!");
                piglog::warning!(
                    "{} {} {}",
                    "Really the ONLY time you should do this is if there is only",
                    "one Rebos process running, but the locking file was never",
                    "cleaned up, so Rebos thinks there is another Rebos process!",
                );

                if bool_question("Are you REALLY sure you want to do this?", false) {
                    piglog::warning!(
                        "Force unlocking... use {} to cancel...",
                        "CTRL + C".bright_red().bold(),
                    );

                    let countdown_from: u8 = 5;

                    print!("Countdown: ");
                    for i in 0..countdown_from {
                        print!("{} ", format!("{}", countdown_from - i).bright_red().bold());
                        io::stdout().flush().unwrap();
                        std::thread::sleep(std::time::Duration::from_secs(1));
                    }
                    print!("\n");

                    match lock::lock_off_force() {
                        Ok(_) => piglog::success!("Unlocked Rebos!"),
                        Err(e) => {
                            piglog::fatal!("Failed to unlock: {e}");

                            return ExitCode::Fail;
                        },
                    };
                }

                else {
                    piglog::info!("Aborting...");

                    return ExitCode::Fail;
                }
            }

            else {
                piglog::info!("Not locked... skipping...");
            }
        },
        cli::Commands::IsUnlocked => {
            match lock::is_lock_on() {
                false => return ExitCode::Success,
                true => return ExitCode::Fail,
            };
        },
        cli::Commands::Managers { command } => {
            match command {
                cli::ManagerCommands::Sync => {
                    match management::sync_all() {
                        Ok(_) => (),
                        Err(_) => return ExitCode::Fail,
                    };
                },
                cli::ManagerCommands::Upgrade { sync } => {
                    match management::upgrade_all(*sync) {
                        Ok(_) => (),
                        Err(_) => return ExitCode::Fail,
                    };
                },
            };
        },
        cli::Commands::API { command } => {
            match command {
                cli::APICommands::Echo { log_mode, message } => {
                    piglog::log_core_print(message.to_string(), *log_mode);
                },
                cli::APICommands::EchoGeneric { message } => {
                    piglog::log_generic_print(message.to_string());
                },
                cli::APICommands::BoolQuestion { question, fallback } => {
                    match bool_question(question, fallback.bool()) {
                        true => return ExitCode::Success,
                        false => return ExitCode::Fail,
                    }
                },
            };
        },
        _ => {
            error!("Command not usable yet!");
            return ExitCode::Fail;
        },
    };

    return ExitCode::Success;
}

// Function that sets up the program.
fn setup() -> Result<(), io::Error> {
    match places::setup() {
        Ok(_) => success!("Core directories verified successfully!"),
        Err(e) => return Err(e),
    };

    return Ok(());
}

// Ask for a yes or no input.
pub fn bool_question<S: AsRef<str>>(question: S, fallback: bool) -> bool {
    let question = question.as_ref();

    let (yes, no) = match fallback {
        true => ("Y".bright_green().bold().underline(), "n".bright_red()),
        false => ("y".bright_green(), "N".bright_red().bold().underline()),
    };

    loop {
        let answer = input(format!(
            "{question} [{yes}/{no}]: ",
            question = question.bright_cyan(),
        ));

        let match_on = answer.trim().to_lowercase();

        match match_on.as_str() {
            "yes" | "y" | "yeah" | "yeh" | "true" => return true,
            "no" | "n" | "nope" | "nah" | "false" => return false,
            "" => return fallback,
            _ => {
                eprintln!("Invalid response: '{}'", match_on);
            },
        }
    }
}

// Ask for user input.
pub fn input<S: AsRef<str>>(prefix: S) -> String {
    let mut answer = String::new();

    print!("{}", prefix.as_ref());

    io::stdout().flush().unwrap();
    io::stdin().read_line(&mut answer).unwrap();

    answer
}