vivo 0.8.0

restic backup orchestrator with multi-remote sync and SOPS-encrypted secrets
Documentation
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
use crossterm::event::{KeyCode, KeyEvent};
use std::{env, process};

use super::app::{App, Pane, FIELD_NAMES};
use super::credentials;
use crate::config_editor::{EditTaskSpec, RemoteSpec, TaskSpec};

fn ensure_path(path: &str) {
    let expanded = crate::backup_config::backup::expand_env_vars(path);
    if !expanded.is_empty() {
        let _ = std::fs::create_dir_all(&expanded);
    }
}

macro_rules! ask {
    ($expr:expr) => {
        match $expr {
            Ok(v) => v,
            Err(
                inquire::InquireError::OperationCanceled
                | inquire::InquireError::OperationInterrupted,
            ) => return Ok("Cancelled.".to_string()),
            Err(e) => return Err(e.to_string()),
        }
    };
}

pub fn handle_key(app: &mut App, key: KeyEvent) {
    match key.code {
        KeyCode::Char('q') | KeyCode::Esc => app.should_quit = true,
        KeyCode::Tab => {
            app.focused_pane = match app.focused_pane {
                Pane::Tasks => Pane::Fields,
                Pane::Fields => Pane::Remotes,
                Pane::Remotes => Pane::Tasks,
            };
            app.status_message = None;
        }
        KeyCode::Enter => {
            if app.focused_pane == Pane::Fields {
                handle_edit_field(app);
            }
        }
        KeyCode::Up => navigate_up(app),
        KeyCode::Down => navigate_down(app),
        KeyCode::Char('a') => handle_add(app),
        KeyCode::Char('d') => handle_delete(app),
        KeyCode::Char('e') => handle_edit(app),
        KeyCode::Char('o') => handle_open_editor(app),
        KeyCode::Char('t') => handle_test_remote(app),
        _ => {}
    }
}

fn navigate_up(app: &mut App) {
    match app.focused_pane {
        Pane::Tasks => {
            if app.selected_task > 0 {
                app.selected_task -= 1;
                app.selected_remote = 0;
                app.selected_field = 0;
            }
        }
        Pane::Fields => {
            if app.selected_field > 0 {
                app.selected_field -= 1;
            }
        }
        Pane::Remotes => {
            if app.selected_remote > 0 {
                app.selected_remote -= 1;
            }
        }
    }
}

fn navigate_down(app: &mut App) {
    match app.focused_pane {
        Pane::Tasks => {
            if app.selected_task + 1 < app.tasks.len() {
                app.selected_task += 1;
                app.selected_remote = 0;
                app.selected_field = 0;
            }
        }
        Pane::Fields => {
            if app.selected_field + 1 < FIELD_NAMES.len() {
                app.selected_field += 1;
            }
        }
        Pane::Remotes => {
            let max = app.current_remotes().len().saturating_sub(1);
            if app.selected_remote < max {
                app.selected_remote += 1;
            }
        }
    }
}

fn suspend_tui() {
    crossterm::terminal::disable_raw_mode().ok();
    crossterm::execute!(std::io::stdout(), crossterm::terminal::LeaveAlternateScreen).ok();
}

fn resume_tui() {
    crossterm::execute!(std::io::stdout(), crossterm::terminal::EnterAlternateScreen).ok();
    crossterm::terminal::enable_raw_mode().ok();
}

/// Suspend the TUI, run `f`, resume, then handle the result.
/// Sets `needs_clear` so the render loop does a full repaint on return.
/// If `reload` is true, reloads config on success. Empty Ok messages are silent.
fn run_prompt(
    app: &mut App,
    f: impl FnOnce(&App) -> Result<String, String>,
    reload: bool,
) {
    suspend_tui();
    let result = f(app);
    resume_tui();
    match result {
        Ok(msg) => {
            if reload {
                app.reload();
            }
            if !msg.is_empty() {
                app.set_status(msg);
            }
        }
        Err(e) => app.set_status(format!("error: {e}")),
    }
    app.needs_clear = true;
}

fn handle_add(app: &mut App) {
    run_prompt(
        app,
        |a| match a.focused_pane {
            Pane::Tasks | Pane::Fields => add_task_prompt(a),
            Pane::Remotes => add_remote_prompt(a),
        },
        true,
    );
}

fn add_task_prompt(app: &App) -> Result<String, String> {
    let name = ask!(inquire::Text::new("Task name:").prompt());
    let repo = ask!(inquire::Text::new("Restic repo path:").prompt());
    let dir_raw = ask!(inquire::Text::new("Directory to back up (blank to skip):")
        .with_help_message("Leave blank to skip")
        .prompt());
    let directory = if dir_raw.is_empty() { None } else { Some(dir_raw) };

    let kdl = std::fs::read_to_string(&app.config_path).map_err(|e| e.to_string())?;
    let new_kdl = crate::config_editor::add_task(
        &kdl,
        TaskSpec { name: name.clone(), repo: repo.clone(), directory: directory.clone(), exclude_file: None },
    )?;
    std::fs::write(&app.config_path, new_kdl).map_err(|e| e.to_string())?;
    ensure_path(&repo);
    if let Some(dir) = &directory {
        ensure_path(dir);
    }
    Ok(format!("Added task '{name}'."))
}

fn restic_url(url: &str) -> String {
    if url.starts_with("rustfs:") {
        url.replacen("rustfs:", "s3:", 1)
    } else {
        url.to_string()
    }
}

pub(crate) fn repo_needs_init(output: &str) -> bool {
    output.contains("Is there a repository")
}

fn offer_repo_init(url: &str, profile: &str, secrets_path: &str) -> Result<String, String> {
    // Decrypt secrets to get credentials for this profile
    let decrypted = match crate::backup_config::decrypt_sops_file(secrets_path) {
        Ok(d) => d,
        Err(_) => return Ok(String::new()), // No sops key available — skip silently
    };
    let secrets = match crate::backup_config::parse_secrets(&decrypted) {
        Ok(s) => s,
        Err(_) => return Ok(String::new()),
    };

    env::set_var("RESTIC_PASSWORD", &secrets.restic_password);

    if let Some(creds) = secrets.credentials.get(profile) {
        for (k, v) in creds {
            env::set_var(k, v);
        }
    }

    let rurl = restic_url(url);

    // Check if a repo exists at this location
    let output = match process::Command::new("restic")
        .args(["-r", &rurl, "snapshots", "--no-lock", "--no-cache"])
        .output()
    {
        Ok(o) => o,
        Err(_) => return Ok(String::new()), // restic not available — skip silently
    };

    if output.status.success() {
        return Ok(String::new()); // Repo already exists
    }

    let combined = format!(
        "{}\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    if !repo_needs_init(&combined) {
        return Ok(String::new()); // Different error (bad creds, network) — skip
    }

    // No repo found — offer to initialize
    let init = match inquire::Confirm::new(&format!(
        "No repository found at '{url}'. Initialize it now?"
    ))
    .with_default(true)
    .prompt()
    {
        Ok(v) => v,
        Err(_) => return Ok(String::new()), // Cancelled — skip silently
    };

    if !init {
        return Ok(String::new());
    }

    println!("\nInitializing repository at {rurl}...");
    let status = process::Command::new("restic")
        .args(["-r", &rurl, "init"])
        .status()
        .map_err(|e| format!("restic init failed: {e}"))?;

    if status.success() {
        Ok("Repository initialized.".to_string())
    } else {
        Err(format!("restic init failed (exit {}).", status.code().unwrap_or(-1)))
    }
}

fn add_remote_prompt(app: &App) -> Result<String, String> {
    let task_name = app
        .tasks
        .get(app.selected_task)
        .map(|t| t.name.clone())
        .ok_or("no task selected")?;

    let url = ask!(inquire::Text::new("Remote URL (e.g. rustfs:http://nas:9000/bucket):").prompt());
    let secrets_path = crate::config::secrets_path_from();
    let credentials = match credentials::select_or_create_profile(&url, &secrets_path)? {
        Some(p) => p,
        None => return Ok("Cancelled.".to_string()),
    };

    let kdl = std::fs::read_to_string(&app.config_path).map_err(|e| e.to_string())?;
    let new_kdl = crate::config_editor::add_remote(
        &kdl,
        &task_name,
        RemoteSpec { url: url.clone(), credentials: credentials.clone() },
    )?;
    std::fs::write(&app.config_path, new_kdl).map_err(|e| e.to_string())?;

    let init_msg = offer_repo_init(&url, &credentials, &secrets_path)?;
    let msg = if init_msg.is_empty() {
        format!("Added remote '{url}' to task '{task_name}'.")
    } else {
        format!("Added remote '{url}' to task '{task_name}'. {init_msg}")
    };
    Ok(msg)
}

fn handle_delete(app: &mut App) {
    if app.focused_pane == Pane::Remotes && app.current_remotes().is_empty() {
        return;
    }
    run_prompt(
        app,
        |a| match a.focused_pane {
            Pane::Tasks | Pane::Fields => delete_task_prompt(a),
            Pane::Remotes => delete_remote_prompt(a),
        },
        true,
    );
}

fn delete_task_prompt(app: &App) -> Result<String, String> {
    let name = app
        .tasks
        .get(app.selected_task)
        .map(|t| t.name.clone())
        .ok_or("no task selected")?;

    let ok = ask!(inquire::Confirm::new(&format!("Remove task '{name}'?"))
        .with_default(false)
        .prompt());
    if !ok {
        return Ok("Cancelled.".to_string());
    }

    let kdl = std::fs::read_to_string(&app.config_path).map_err(|e| e.to_string())?;
    let new_kdl = crate::config_editor::remove_task(&kdl, &name)?;
    std::fs::write(&app.config_path, new_kdl).map_err(|e| e.to_string())?;
    Ok(format!("Removed task '{name}'."))
}

fn delete_remote_prompt(app: &App) -> Result<String, String> {
    let task_name = app
        .tasks
        .get(app.selected_task)
        .map(|t| t.name.clone())
        .ok_or("no task selected")?;
    let url = app
        .current_remotes()
        .get(app.selected_remote)
        .map(|r| r.url.clone())
        .ok_or("no remote selected")?;

    let ok = ask!(inquire::Confirm::new(&format!(
        "Remove remote '{url}' from task '{task_name}'?"
    ))
    .with_default(false)
    .prompt());
    if !ok {
        return Ok("Cancelled.".to_string());
    }

    let kdl = std::fs::read_to_string(&app.config_path).map_err(|e| e.to_string())?;
    let new_kdl = crate::config_editor::remove_remote(&kdl, &task_name, &url)?;
    std::fs::write(&app.config_path, new_kdl).map_err(|e| e.to_string())?;
    Ok(format!("Removed remote '{url}'."))
}

fn handle_open_editor(app: &mut App) {
    let editor = env::var("EDITOR").unwrap_or_else(|_| "vi".to_string());
    run_prompt(
        app,
        |a| {
            process::Command::new(&editor).arg(&a.config_path).status().ok();
            Ok(String::new())
        },
        true,
    );
}

fn handle_edit(app: &mut App) {
    match app.focused_pane {
        Pane::Fields => handle_edit_field(app),
        Pane::Tasks => run_prompt(app, edit_task_prompt, true),
        Pane::Remotes => {
            if app.current_remotes().is_empty() {
                return;
            }
            run_prompt(app, edit_remote_prompt, true);
        }
    }
}

fn handle_edit_field(app: &mut App) {
    run_prompt(app, edit_field_prompt, true);
}

fn handle_test_remote(app: &mut App) {
    if app.focused_pane != Pane::Remotes || app.current_remotes().is_empty() {
        return;
    }
    run_prompt(app, test_remote_prompt, false);
}

fn test_remote_prompt(app: &App) -> Result<String, String> {
    let remote = app
        .current_remotes()
        .get(app.selected_remote)
        .ok_or("no remote selected")?;
    let url = remote.url.clone();
    let profile = remote.credentials.clone();

    let secrets_path = crate::config::secrets_path_from();
    println!("Decrypting secrets from {secrets_path}...");
    let decrypted =
        crate::backup_config::decrypt_sops_file(&secrets_path).map_err(|e| e.to_string())?;
    let secrets =
        crate::backup_config::parse_secrets(&decrypted).map_err(|e| e.to_string())?;

    env::set_var("RESTIC_PASSWORD", &secrets.restic_password);

    let creds = secrets.credentials.get(&profile).ok_or_else(|| {
        format!("credentials profile '{profile}' not found in secrets")
    })?;
    for (k, v) in creds {
        env::set_var(k, v);
    }

    println!("\nTesting remote: {url}");
    println!("Credentials:    {profile}\n");

    let (status, restic_output) = if url.starts_with("b2:") {
        let path = url.trim_start_matches("b2:").trim_start_matches('/');
        let s = process::Command::new("b2")
            .args(["ls", path])
            .status()
            .map_err(|e| format!("could not run b2: {e}"))?;
        (s, String::new())
    } else {
        let rurl = restic_url(&url);
        let out = process::Command::new("restic")
            .args(["-r", &rurl, "snapshots", "--no-lock", "--no-cache"])
            .output()
            .map_err(|e| format!("could not run restic: {e}"))?;
        print!("{}", String::from_utf8_lossy(&out.stdout));
        print!("{}", String::from_utf8_lossy(&out.stderr));
        let combined = format!(
            "{}\n{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
        (out.status, combined)
    };

    println!();
    let mut summary = if status.success() {
        "Remote test passed.".to_string()
    } else {
        format!("Remote test failed (exit {}).", status.code().unwrap_or(-1))
    };
    println!("{summary}");

    if !status.success() && repo_needs_init(&restic_output) {
        let secrets_path = crate::config::secrets_path_from();
        match offer_repo_init(&url, &profile, &secrets_path) {
            Ok(msg) if !msg.is_empty() => {
                summary = msg.clone();
                println!("{msg}");
            }
            Err(e) => println!("Init failed: {e}"),
            _ => {}
        }
    }

    println!("\nPress Enter to return...");
    std::io::stdin().read_line(&mut String::new()).ok();

    Ok(summary)
}

fn edit_field_prompt(app: &App) -> Result<String, String> {
    let task = app.tasks.get(app.selected_task).ok_or("no task selected")?;
    let old_name = task.name.clone();

    let mut name = task.name.clone();
    let mut description = task.description.clone();
    let mut repo = task.repo.clone();
    let mut directory = task.directory.clone();
    let mut exclude_file = task.exclude_file.clone();
    let mut files_from = task.files_from.clone();

    if app.selected_field >= 3 && task.repo.is_none() {
        return Err("set a repo path first".to_string());
    }

    match app.selected_field {
        0 => {
            let v = ask!(inquire::Text::new("Task name:").with_initial_value(&name).prompt());
            if v.trim().is_empty() {
                return Err("task name cannot be empty".to_string());
            }
            name = v;
        }
        1 => {
            let v = ask!(inquire::Text::new("Description (blank = none):")
                .with_initial_value(description.as_deref().unwrap_or(""))
                .prompt());
            description = if v.is_empty() { None } else { Some(v) };
        }
        2 => {
            let v = ask!(inquire::Text::new("Repo path (blank = none):")
                .with_initial_value(repo.as_deref().unwrap_or(""))
                .prompt());
            repo = if v.is_empty() { None } else { Some(v) };
        }
        3 => {
            let v = ask!(inquire::Text::new("Directory (blank = none):")
                .with_initial_value(directory.as_deref().unwrap_or(""))
                .prompt());
            directory = if v.is_empty() { None } else { Some(v) };
        }
        4 => {
            let v = ask!(inquire::Text::new("Exclude file (blank = none):")
                .with_initial_value(exclude_file.as_deref().unwrap_or(""))
                .prompt());
            exclude_file = if v.is_empty() { None } else { Some(v) };
        }
        5 => {
            let v = ask!(inquire::Text::new("Files from (blank = none):")
                .with_initial_value(files_from.as_deref().unwrap_or(""))
                .prompt());
            files_from = if v.is_empty() { None } else { Some(v) };
        }
        _ => return Ok(String::new()),
    }

    let repo_path = repo.clone();
    let dir_path = directory.clone();
    let kdl = std::fs::read_to_string(&app.config_path).map_err(|e| e.to_string())?;
    let new_kdl = crate::config_editor::edit_task(
        &kdl,
        &old_name,
        EditTaskSpec { name: name.clone(), description, repo, directory, exclude_file, files_from },
    )?;
    std::fs::write(&app.config_path, new_kdl).map_err(|e| e.to_string())?;
    if let Some(r) = repo_path { ensure_path(&r); }
    if let Some(d) = dir_path { ensure_path(&d); }
    Ok(format!("Updated '{name}'."))
}

fn edit_task_prompt(app: &App) -> Result<String, String> {
    let task = app.tasks.get(app.selected_task).ok_or("no task selected")?;
    let old_name = task.name.clone();

    let name = ask!(inquire::Text::new("Task name:")
        .with_initial_value(&task.name)
        .prompt());

    if name.is_empty() {
        return Err("task name cannot be empty".to_string());
    }

    let desc_default = task.description.clone().unwrap_or_default();
    let desc_raw = ask!(inquire::Text::new("Description (blank = none):")
        .with_initial_value(&desc_default)
        .prompt());
    let description = if desc_raw.is_empty() { None } else { Some(desc_raw) };

    let (repo, directory, exclude_file, files_from) = if task.repo.is_some() {
        let repo = ask!(inquire::Text::new("Repo path:")
            .with_initial_value(task.repo.as_deref().unwrap_or(""))
            .prompt());

        let dir_raw = ask!(inquire::Text::new("Directory (blank = none):")
            .with_initial_value(task.directory.as_deref().unwrap_or(""))
            .prompt());
        let directory = if dir_raw.is_empty() { None } else { Some(dir_raw) };

        let excl_raw = ask!(inquire::Text::new("Exclude file (blank = none):")
            .with_initial_value(task.exclude_file.as_deref().unwrap_or(""))
            .prompt());
        let exclude_file = if excl_raw.is_empty() { None } else { Some(excl_raw) };

        let ff_raw = ask!(inquire::Text::new("Files from (blank = none):")
            .with_initial_value(task.files_from.as_deref().unwrap_or(""))
            .prompt());
        let files_from = if ff_raw.is_empty() { None } else { Some(ff_raw) };

        (Some(repo), directory, exclude_file, files_from)
    } else {
        (None, None, None, None)
    };

    let repo_path = repo.clone();
    let dir_path = directory.clone();
    let kdl = std::fs::read_to_string(&app.config_path).map_err(|e| e.to_string())?;
    let new_kdl = crate::config_editor::edit_task(
        &kdl,
        &old_name,
        EditTaskSpec { name: name.clone(), description, repo, directory, exclude_file, files_from },
    )?;
    std::fs::write(&app.config_path, new_kdl).map_err(|e| e.to_string())?;
    if let Some(r) = repo_path { ensure_path(&r); }
    if let Some(d) = dir_path { ensure_path(&d); }
    Ok(format!("Updated task '{name}'."))
}

fn edit_remote_prompt(app: &App) -> Result<String, String> {
    let task_name = app
        .tasks
        .get(app.selected_task)
        .map(|t| t.name.clone())
        .ok_or("no task selected")?;
    let remote = app
        .current_remotes()
        .get(app.selected_remote)
        .ok_or("no remote selected")?;
    let old_url = remote.url.clone();

    let url = ask!(inquire::Text::new("Remote URL:")
        .with_initial_value(&remote.url)
        .prompt());
    if url.trim().is_empty() {
        return Err("remote URL cannot be empty".to_string());
    }

    let secrets_path = crate::config::secrets_path_from();
    let credentials = match credentials::select_or_create_profile(&url, &secrets_path)? {
        Some(p) => p,
        None => return Ok("Cancelled.".to_string()),
    };

    let kdl = std::fs::read_to_string(&app.config_path).map_err(|e| e.to_string())?;
    let new_kdl = crate::config_editor::edit_remote(
        &kdl,
        &task_name,
        &old_url,
        RemoteSpec { url: url.clone(), credentials: credentials.clone() },
    )?;
    std::fs::write(&app.config_path, new_kdl).map_err(|e| e.to_string())?;

    let init_msg = offer_repo_init(&url, &credentials, &secrets_path)?;
    let msg = if init_msg.is_empty() {
        "Updated remote.".to_string()
    } else {
        format!("Updated remote. {init_msg}")
    };
    Ok(msg)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn repo_needs_init_detects_missing_repo() {
        let output = "Fatal: unable to open config file: Stat: The specified key does not exist.\nIs there a repository at the following location?\ns3:https://example.com/bucket\n";
        assert!(repo_needs_init(output));
    }

    #[test]
    fn repo_needs_init_false_for_other_errors() {
        let output = "Fatal: unable to open config file: Forbidden\n";
        assert!(!repo_needs_init(output));
    }

    #[test]
    fn repo_needs_init_false_for_success() {
        let output = "snapshot abc123 ...\n";
        assert!(!repo_needs_init(output));
    }
}