vm-curator 0.4.3

A TUI application to manage QEMU VM library
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
mod app;
mod commands;
mod config;
mod fs;
mod hardware;
mod metadata;
mod ui;
mod vm;

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use crossterm::{
    event::{DisableMouseCapture, EnableMouseCapture},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::prelude::*;
use std::io::{self, Write};
use std::path::PathBuf;

use app::App;
use config::Config;

#[derive(Parser)]
#[command(name = "vm-curator")]
#[command(author = "Mark Roboff")]
#[command(version)]
#[command(about = "A TUI application to manage your QEMU VM library")]
struct Cli {
    /// Path to VM library directory
    #[arg(short, long)]
    library: Option<PathBuf>,

    /// Subcommand to run
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// List all VMs in the library
    List,

    /// Launch a VM by name
    Launch {
        /// VM name or ID
        name: String,
        /// Boot in install mode
        #[arg(short, long)]
        install: bool,
        /// Boot with custom ISO
        #[arg(short, long)]
        cdrom: Option<PathBuf>,
    },

    /// Show VM configuration
    Info {
        /// VM name or ID
        name: String,
    },

    /// Manage snapshots
    Snapshot {
        /// VM name or ID
        name: String,
        #[command(subcommand)]
        action: SnapshotAction,
    },

    /// List available QEMU emulators
    Emulators,
}

#[derive(Subcommand)]
enum SnapshotAction {
    /// List snapshots
    List,
    /// Create a snapshot
    Create {
        /// Snapshot name
        snapshot_name: String,
    },
    /// Restore a snapshot
    Restore {
        /// Snapshot name
        snapshot_name: String,
    },
    /// Delete a snapshot
    Delete {
        /// Snapshot name
        snapshot_name: String,
    },
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    // Load configuration
    let mut config = Config::load()?;

    // Override library path if provided
    if let Some(ref library) = cli.library {
        config.vm_library_path = library.clone();
    }

    // Check if VM library exists, prompt for setup if not
    if !config.vm_library_path.exists() {
        config = prompt_vm_library_setup(config)?;
    }

    // Handle subcommands
    match cli.command {
        Some(Commands::List) => cmd_list(&config),
        Some(Commands::Launch { name, install, cdrom }) => cmd_launch(&config, &name, install, cdrom),
        Some(Commands::Info { name }) => cmd_info(&config, &name),
        Some(Commands::Snapshot { name, action }) => cmd_snapshot(&config, &name, action),
        Some(Commands::Emulators) => cmd_emulators(),
        None => run_tui(config),
    }
}

/// Prompt user to set up VM library directory
fn prompt_vm_library_setup(mut config: Config) -> Result<Config> {
    println!();
    println!("\x1b[1;36m╭─────────────────────────────────────╮\x1b[0m");
    println!("\x1b[1;36m│\x1b[0m    \x1b[1;33mVM Curator\x1b[0m - First Time Setup    \x1b[1;36m│\x1b[0m");
    println!("\x1b[1;36m╰─────────────────────────────────────╯\x1b[0m");
    println!();
    println!("VM library directory not found.");
    println!();

    // Show default path with ~ for home
    let default_path = config.vm_library_path.display().to_string();
    let display_path = if let Some(home) = dirs::home_dir() {
        default_path.replace(&home.display().to_string(), "~")
    } else {
        default_path.clone()
    };

    println!("Where should VMs be stored?");
    println!("\x1b[90mPress Enter to use default, or type a new path.\x1b[0m");
    println!();
    print!("\x1b[1;32m[\x1b[0m{}\x1b[1;32m]\x1b[0m: ", display_path);
    io::stdout().flush()?;

    // Read user input
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    let input = input.trim();

    // Use input if provided, otherwise keep default
    if !input.is_empty() {
        // Expand ~ to home directory
        let expanded = if let Some(rest) = input.strip_prefix("~/") {
            if let Some(home) = dirs::home_dir() {
                home.join(rest)
            } else {
                PathBuf::from(input)
            }
        } else if input == "~" {
            dirs::home_dir().unwrap_or_else(|| PathBuf::from(input))
        } else {
            PathBuf::from(input)
        };
        config.vm_library_path = expanded;
    }

    // Create the directory
    println!();
    print!("Creating directory {:?}... ", config.vm_library_path);
    io::stdout().flush()?;

    let cow_disabled = fs::setup_vm_directory(&config.vm_library_path)
        .with_context(|| format!("Failed to create VM library directory {:?}", config.vm_library_path))?;

    println!("\x1b[32m✓\x1b[0m");

    if cow_disabled {
        println!("Disabled BTRFS copy-on-write for better VM performance \x1b[32m✓\x1b[0m");
    }

    // Save configuration
    print!("Saving configuration... ");
    io::stdout().flush()?;

    config.save()?;

    println!("\x1b[32m✓\x1b[0m");
    println!();

    Ok(config)
}

/// Guard that ensures terminal is restored on drop (even on panic)
struct TerminalGuard;

impl Drop for TerminalGuard {
    fn drop(&mut self) {
        // Best effort restoration - ignore errors since we may be panicking
        let _ = disable_raw_mode();
        let _ = execute!(
            io::stdout(),
            LeaveAlternateScreen,
            DisableMouseCapture
        );
        let _ = crossterm::cursor::Show;
    }
}

fn run_tui(config: Config) -> Result<()> {
    // Show loading screen before entering TUI
    print_loading_header();

    // Create app state with progress updates
    let app = App::new_with_progress(config, |step, total, msg| {
        print_loading_progress(step, total, msg);
    })?;

    // Clear loading screen
    print!("\r\x1b[K"); // Clear line
    println!("\x1b[32m✓\x1b[0m Ready! Starting TUI...");
    std::thread::sleep(std::time::Duration::from_millis(150));

    // Setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;

    // Create guard AFTER setup so it only cleans up if setup succeeded
    let _guard = TerminalGuard;

    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    // Run the app - guard will restore terminal even if this panics
    let mut app = app;
    ui::run(&mut terminal, &mut app)
}

fn print_loading_header() {
    println!();
    println!("\x1b[1;36m╭─────────────────────────────────────╮\x1b[0m");
    println!("\x1b[1;36m│\x1b[0m    \x1b[1;33mVM Curator\x1b[0m - QEMU VM Manager     \x1b[1;36m│\x1b[0m");
    println!("\x1b[1;36m╰─────────────────────────────────────╯\x1b[0m");
    println!();
}

fn print_loading_progress(step: usize, total: usize, message: &str) {
    use std::io::Write;

    let bar_width = 30;
    let filled = (step * bar_width) / total;
    let empty = bar_width - filled;

    let bar: String = "â–ˆ".repeat(filled) + &"â–‘".repeat(empty);
    let percent = (step * 100) / total;

    print!("\r\x1b[K"); // Clear line
    print!("\x1b[90m[\x1b[36m{}\x1b[90m]\x1b[0m {:>3}% {}", bar, percent, message);
    let _ = io::stdout().flush();
}

fn cmd_list(config: &Config) -> Result<()> {
    let vms = vm::discover_vms(&config.vm_library_path)?;

    if vms.is_empty() {
        println!("No VMs found in {:?}", config.vm_library_path);
        return Ok(());
    }

    println!("VMs in {:?}:", config.vm_library_path);
    println!();

    let groups = vm::group_vms_by_category(&vms);
    for (category, group_vms) in groups {
        println!("{}:", category);
        for vm in group_vms {
            let arch = vm.config.emulator.architecture();
            let mem = vm.config.memory_mb;
            let snapshot_support = if vm.config.supports_snapshots() {
                "[snapshots]"
            } else {
                ""
            };
            println!(
                "  {:24} {:8} {:4}MB {}",
                vm.display_name(),
                arch,
                mem,
                snapshot_support
            );
        }
        println!();
    }

    println!("Total: {} VMs", vms.len());
    Ok(())
}

fn cmd_launch(config: &Config, name: &str, install: bool, cdrom: Option<PathBuf>) -> Result<()> {
    let vms = vm::discover_vms(&config.vm_library_path)?;

    let vm = vms
        .iter()
        .find(|v| v.id == name || v.display_name().to_lowercase() == name.to_lowercase())
        .ok_or_else(|| anyhow::anyhow!("VM '{}' not found", name))?;

    let boot_mode = if let Some(iso) = cdrom {
        vm::BootMode::Cdrom(iso)
    } else if install {
        vm::BootMode::Install
    } else {
        vm::BootMode::Normal
    };

    let options = vm::LaunchOptions {
        boot_mode,
        extra_args: Vec::new(),
        usb_devices: Vec::new(),
    };

    println!("Launching {}...", vm.display_name());
    vm::launch_vm_sync(vm, &options)?;
    println!("VM started.");

    Ok(())
}

fn cmd_info(config: &Config, name: &str) -> Result<()> {
    let vms = vm::discover_vms(&config.vm_library_path)?;

    let vm = vms
        .iter()
        .find(|v| v.id == name || v.display_name().to_lowercase() == name.to_lowercase())
        .ok_or_else(|| anyhow::anyhow!("VM '{}' not found", name))?;

    println!("VM: {}", vm.display_name());
    println!("ID: {}", vm.id);
    println!("Path: {:?}", vm.path);
    println!();
    println!("Configuration:");
    println!("  Emulator: {}", vm.config.emulator.command());
    println!("  Architecture: {}", vm.config.emulator.architecture());
    println!("  Memory: {} MB", vm.config.memory_mb);
    println!("  CPU Cores: {}", vm.config.cpu_cores);

    if let Some(ref model) = vm.config.cpu_model {
        println!("  CPU Model: {}", model);
    }
    if let Some(ref machine) = vm.config.machine {
        println!("  Machine: {}", machine);
    }

    println!("  VGA: {:?}", vm.config.vga);
    println!("  KVM: {}", vm.config.enable_kvm);
    println!("  UEFI: {}", vm.config.uefi);
    println!("  TPM: {}", vm.config.tpm);

    println!();
    println!("Disks:");
    for disk in &vm.config.disks {
        println!(
            "  {:?} ({:?}, {})",
            disk.path, disk.format, disk.interface
        );
    }

    println!();
    println!("Snapshots supported: {}", vm.config.supports_snapshots());

    if vm.config.supports_snapshots() {
        if let Some(disk) = vm.config.primary_disk() {
            let snapshots = vm::list_snapshots(&disk.path)?;
            if !snapshots.is_empty() {
                println!();
                println!("Snapshots:");
                for snap in snapshots {
                    println!("  {} ({}, {})", snap.name, snap.date, snap.size);
                }
            }
        }
    }

    Ok(())
}

fn cmd_snapshot(config: &Config, name: &str, action: SnapshotAction) -> Result<()> {
    let vms = vm::discover_vms(&config.vm_library_path)?;

    let vm = vms
        .iter()
        .find(|v| v.id == name || v.display_name().to_lowercase() == name.to_lowercase())
        .ok_or_else(|| anyhow::anyhow!("VM '{}' not found", name))?;

    if !vm.config.supports_snapshots() {
        anyhow::bail!("VM '{}' does not support snapshots (raw disk format)", name);
    }

    let disk = vm
        .config
        .primary_disk()
        .ok_or_else(|| anyhow::anyhow!("VM has no disk configured"))?;

    match action {
        SnapshotAction::List => {
            let snapshots = vm::list_snapshots(&disk.path)?;
            if snapshots.is_empty() {
                println!("No snapshots for {}", vm.display_name());
            } else {
                println!("Snapshots for {}:", vm.display_name());
                for snap in snapshots {
                    println!("  {} ({}, {})", snap.name, snap.date, snap.size);
                }
            }
        }
        SnapshotAction::Create { snapshot_name } => {
            println!("Creating snapshot '{}'...", snapshot_name);
            vm::create_snapshot(&disk.path, &snapshot_name)?;
            println!("Snapshot created.");
        }
        SnapshotAction::Restore { snapshot_name } => {
            println!("Restoring snapshot '{}'...", snapshot_name);
            vm::restore_snapshot(&disk.path, &snapshot_name)?;
            println!("Snapshot restored.");
        }
        SnapshotAction::Delete { snapshot_name } => {
            println!("Deleting snapshot '{}'...", snapshot_name);
            vm::delete_snapshot(&disk.path, &snapshot_name)?;
            println!("Snapshot deleted.");
        }
    }

    Ok(())
}

fn cmd_emulators() -> Result<()> {
    println!("Available QEMU emulators:");
    println!();

    let emulators = commands::qemu_system::list_available_emulators();

    if emulators.is_empty() {
        println!("  No QEMU emulators found. Please install QEMU.");
        return Ok(());
    }

    for emulator in emulators {
        if let Ok(version) = commands::qemu_system::get_qemu_version(&emulator) {
            println!("  {} - {}", emulator, version);
        } else {
            println!("  {}", emulator);
        }
    }

    println!();

    if commands::qemu_system::is_kvm_available() {
        if let Some(module) = commands::qemu_system::get_kvm_info() {
            println!("KVM: available ({})", module);
        } else {
            println!("KVM: available");
        }
    } else {
        println!("KVM: not available");
    }

    Ok(())
}