vm-curator 0.4.2

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
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
use anyhow::Result;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use super::qemu_config::*;
use crate::commands::qemu_img;

/// Parse a launch.sh script and extract QEMU configuration
pub fn parse_launch_script(script_path: &Path, content: &str) -> Result<QemuConfig> {
    let mut config = QemuConfig {
        raw_script: content.to_string(),
        ..Default::default()
    };

    let vm_dir = script_path.parent().unwrap_or(Path::new("."));

    // Extract emulator
    if let Some(emulator) = extract_emulator(content) {
        config.emulator = emulator;
    }

    // Extract memory
    if let Some(mem) = extract_memory(content) {
        config.memory_mb = mem;
    }

    // Extract CPU cores
    if let Some(cores) = extract_cpu_cores(content) {
        config.cpu_cores = cores;
    }

    // Extract CPU model
    config.cpu_model = extract_cpu_model(content);

    // Extract machine type
    config.machine = extract_machine(content);

    // Extract VGA
    if let Some(vga) = extract_vga(content) {
        config.vga = vga;
    }

    // Extract audio devices
    config.audio_devices = extract_audio_devices(content);

    // Check for KVM
    config.enable_kvm = content.contains("-enable-kvm") || content.contains("-accel kvm");

    // Check for UEFI
    config.uefi = content.contains("OVMF") || content.contains("-bios") && content.contains("efi");

    // Check for TPM
    config.tpm = content.contains("-tpmdev") || content.contains("swtpm");

    // Extract BIOS/ROM path (for classic Mac and other custom firmware)
    config.bios_path = extract_bios_path(content, vm_dir);

    // Extract disks
    config.disks = extract_disks(content, vm_dir);

    // Extract network config
    config.network = extract_network(content);

    // Extract extra arguments we don't specifically parse
    config.extra_args = extract_extra_args(content);

    Ok(config)
}

/// Extract the QEMU emulator command
fn extract_emulator(content: &str) -> Option<QemuEmulator> {
    let emulators = [
        "qemu-system-x86_64",
        "qemu-system-i386",
        "qemu-system-ppc",
        "qemu-system-m68k",
        "qemu-system-arm",
        "qemu-system-aarch64",
    ];

    for emulator in emulators {
        if content.contains(emulator) {
            return Some(QemuEmulator::from_command(emulator));
        }
    }
    None
}

/// Extract memory configuration
fn extract_memory(content: &str) -> Option<u32> {
    for line in content.lines() {
        // Skip comments
        if line.trim_start().starts_with('#') {
            continue;
        }

        // Look for -m flag
        if let Some(idx) = line.find("-m ") {
            let rest = &line[idx + 3..];
            let value: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
            if let Ok(mem) = value.parse::<u32>() {
                // Check for G suffix
                if rest.contains('G') {
                    return Some(mem * 1024);
                }
                // If less than 64, probably gigabytes
                if mem < 64 {
                    return Some(mem * 1024);
                }
                return Some(mem);
            }
        }
    }
    None
}

/// Extract CPU cores
fn extract_cpu_cores(content: &str) -> Option<u32> {
    for line in content.lines() {
        if line.trim_start().starts_with('#') {
            continue;
        }

        // Look for -smp
        if let Some(idx) = line.find("-smp ") {
            let rest = &line[idx + 5..];
            let value: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
            if let Ok(cores) = value.parse::<u32>() {
                return Some(cores);
            }
        }
    }
    None
}

/// Extract CPU model
fn extract_cpu_model(content: &str) -> Option<String> {
    for line in content.lines() {
        if line.trim_start().starts_with('#') {
            continue;
        }

        if let Some(idx) = line.find("-cpu ") {
            let rest = &line[idx + 5..];
            let model: String = rest
                .chars()
                .take_while(|c| !c.is_whitespace() && *c != '\\')
                .collect();
            if !model.is_empty() {
                return Some(model);
            }
        }
    }
    None
}

/// Extract machine type
fn extract_machine(content: &str) -> Option<String> {
    for line in content.lines() {
        if line.trim_start().starts_with('#') {
            continue;
        }

        if let Some(idx) = line.find("-M ") {
            let rest = &line[idx + 3..];
            let machine: String = rest
                .chars()
                .take_while(|c| !c.is_whitespace() && *c != '\\')
                .collect();
            if !machine.is_empty() {
                return Some(machine);
            }
        }

        if let Some(idx) = line.find("-machine ") {
            let rest = &line[idx + 9..];
            let machine: String = rest
                .chars()
                .take_while(|c| !c.is_whitespace() && *c != ',' && *c != '\\')
                .collect();
            if !machine.is_empty() {
                return Some(machine);
            }
        }
    }
    None
}

/// Extract VGA type
fn extract_vga(content: &str) -> Option<VgaType> {
    for line in content.lines() {
        if line.trim_start().starts_with('#') {
            continue;
        }

        if let Some(idx) = line.find("-vga ") {
            let rest = &line[idx + 5..];
            let vga: String = rest
                .chars()
                .take_while(|c| !c.is_whitespace() && *c != '\\')
                .collect();
            if !vga.is_empty() {
                return Some(VgaType::from_str(&vga));
            }
        }
    }
    None
}

/// Extract audio devices
fn extract_audio_devices(content: &str) -> Vec<AudioDevice> {
    let mut devices = Vec::new();

    // Check for SoundBlaster 16
    if content.contains("sb16") || content.contains("SB16") {
        devices.push(AudioDevice::Sb16);
    }

    // Check for AC97
    if content.contains("ac97") || content.contains("AC97") {
        devices.push(AudioDevice::Ac97);
    }

    // Check for Intel HDA
    if content.contains("intel-hda") || content.contains("hda-duplex") {
        devices.push(AudioDevice::Hda);
    }

    // Check for ES1370
    if content.contains("es1370") {
        devices.push(AudioDevice::Es1370);
    }

    devices
}

/// Extract shell variable assignments from the script
fn extract_shell_variables(content: &str, vm_dir: &Path) -> HashMap<String, String> {
    let mut vars = HashMap::new();

    // Pre-populate with common directory variables
    let vm_dir_str = vm_dir.to_string_lossy().to_string();
    vars.insert("VM_DIR".to_string(), vm_dir_str.clone());
    vars.insert("DIR".to_string(), vm_dir_str.clone());

    // Parse variable assignments like: VAR="value" or VAR='value' or VAR=value
    for line in content.lines() {
        let trimmed = line.trim();

        // Skip comments and empty lines
        if trimmed.starts_with('#') || trimmed.is_empty() {
            continue;
        }

        // Look for variable assignments (NAME=value pattern)
        if let Some(eq_pos) = trimmed.find('=') {
            let name = trimmed[..eq_pos].trim();

            // Variable names must be valid shell identifiers
            if !name.is_empty()
                && name.chars().all(|c| c.is_alphanumeric() || c == '_')
                && !name.chars().next().unwrap_or('0').is_ascii_digit()
            {
                let value_part = trimmed[eq_pos + 1..].trim();

                // Extract the value, handling quotes with proper nesting
                let value = extract_quoted_value(value_part);

                // Expand any variables in the value
                let expanded = expand_variables(&value, &vars, vm_dir);
                vars.insert(name.to_string(), expanded);
            }
        }
    }

    vars
}

/// Extract a quoted value, handling nested quotes and command substitutions
fn extract_quoted_value(s: &str) -> String {
    if s.starts_with('"') {
        // Find the matching closing quote, accounting for nested quotes in $()
        let chars: Vec<char> = s.chars().collect();
        let mut depth = 0;
        let mut end_idx = s.len() - 1;

        for (i, &c) in chars.iter().enumerate().skip(1) {
            match c {
                '(' if i > 0 && chars[i - 1] == '$' => depth += 1,
                ')' if depth > 0 => depth -= 1,
                '"' if depth == 0 => {
                    end_idx = i;
                    break;
                }
                _ => {}
            }
        }

        s[1..end_idx].to_string()
    } else if let Some(stripped) = s.strip_prefix('\'') {
        // Single quotes don't nest - find first closing quote
        if let Some(end) = stripped.find('\'') {
            stripped[..end].to_string()
        } else {
            stripped.to_string()
        }
    } else {
        // Unquoted value - take until whitespace or comment
        s.chars()
            .take_while(|c| !c.is_whitespace() && *c != '#')
            .collect()
    }
}

/// Expand shell variables in a string
fn expand_variables(s: &str, vars: &HashMap<String, String>, vm_dir: &Path) -> String {
    let mut result = s.to_string();
    let vm_dir_str = vm_dir.to_string_lossy();

    // Handle $(dirname ...) patterns - replace with vm_dir
    while result.contains("$(dirname") {
        if let Some(start) = result.find("$(dirname") {
            // Find matching closing paren
            let mut depth = 0;
            let mut end = start;
            for (i, c) in result[start..].char_indices() {
                match c {
                    '(' => depth += 1,
                    ')' => {
                        depth -= 1;
                        if depth == 0 {
                            end = start + i;
                            break;
                        }
                    }
                    _ => {}
                }
            }
            if end > start {
                result = format!("{}{}{}", &result[..start], vm_dir_str, &result[end + 1..]);
            } else {
                break;
            }
        } else {
            break;
        }
    }

    // Expand ${VAR} format
    for (name, value) in vars {
        result = result.replace(&format!("${{{}}}", name), value);
    }

    // Expand $VAR format (must be done after ${VAR} to avoid partial matches)
    for (name, value) in vars {
        result = result.replace(&format!("${}", name), value);
    }

    // Handle $HOME
    if result.contains("$HOME") || result.contains("${HOME}") {
        if let Some(home) = dirs::home_dir() {
            let home_str = home.to_string_lossy();
            result = result.replace("${HOME}", &home_str);
            result = result.replace("$HOME", &home_str);
        }
    }

    result
}

/// Extract disk configurations
fn extract_disks(content: &str, vm_dir: &Path) -> Vec<DiskConfig> {
    let mut disks = Vec::new();

    // First, parse all variable assignments
    let vars = extract_shell_variables(content, vm_dir);

    for line in content.lines() {
        if line.trim_start().starts_with('#') {
            continue;
        }

        // Look for -hda, -hdb, etc.
        for hd in ["hda", "hdb", "hdc", "hdd"] {
            let pattern = format!("-{} ", hd);
            if let Some(idx) = line.find(&pattern) {
                let rest = &line[idx + pattern.len()..];
                if let Some(path) = extract_path_from_arg(rest) {
                    let expanded = expand_variables(&path, &vars, vm_dir);
                    let full_path = resolve_path(&expanded, vm_dir);
                    let format = guess_disk_format(&full_path);
                    disks.push(DiskConfig {
                        path: full_path,
                        format,
                        interface: "ide".to_string(),
                    });
                }
            }
        }

        // Look for -drive file=
        if line.contains("-drive") && line.contains("file=") {
            if let Some(path) = extract_drive_file(line) {
                let expanded = expand_variables(&path, &vars, vm_dir);
                let full_path = resolve_path(&expanded, vm_dir);
                let format = guess_disk_format(&full_path);
                let interface = if line.contains("if=virtio") {
                    "virtio"
                } else if line.contains("if=scsi") {
                    "scsi"
                } else {
                    "ide"
                };
                disks.push(DiskConfig {
                    path: full_path,
                    format,
                    interface: interface.to_string(),
                });
            }
        }
    }

    disks
}

/// Extract file path from -drive file= argument
fn extract_drive_file(line: &str) -> Option<String> {
    if let Some(idx) = line.find("file=") {
        let rest = &line[idx + 5..];
        // Handle quoted paths
        if let Some(inner) = rest.strip_prefix('"') {
            let end = inner.find('"')?;
            return Some(inner[..end].to_string());
        }
        // Handle unquoted paths
        let path: String = rest
            .chars()
            .take_while(|c| !c.is_whitespace() && *c != ',' && *c != '\\')
            .collect();
        if !path.is_empty() {
            return Some(path);
        }
    }
    None
}

/// Extract a path from an argument
fn extract_path_from_arg(arg: &str) -> Option<String> {
    let trimmed = arg.trim();
    if let Some(inner) = trimmed.strip_prefix('"') {
        let end = inner.find('"')?;
        return Some(inner[..end].to_string());
    }
    if let Some(inner) = trimmed.strip_prefix('\'') {
        let end = inner.find('\'')?;
        return Some(inner[..end].to_string());
    }
    let path: String = trimmed
        .chars()
        .take_while(|c| !c.is_whitespace() && *c != '\\')
        .collect();
    if !path.is_empty() && !path.starts_with('-') {
        Some(path)
    } else {
        None
    }
}

/// Resolve a path relative to VM directory
fn resolve_path(path: &str, vm_dir: &Path) -> PathBuf {
    let path = path.replace("$DIR", &vm_dir.to_string_lossy());
    let path = path.replace("${DIR}", &vm_dir.to_string_lossy());
    let path = path.replace("$(dirname $0)", &vm_dir.to_string_lossy());

    let p = PathBuf::from(&path);
    if p.is_absolute() {
        p
    } else {
        vm_dir.join(p)
    }
}

/// Detect disk format using qemu-img info, falling back to extension-based guessing
fn guess_disk_format(path: &Path) -> DiskFormat {
    // First, try to detect the actual format using qemu-img info
    if path.exists() {
        if let Some(format_str) = qemu_img::detect_disk_format(path) {
            return match format_str.to_lowercase().as_str() {
                "qcow2" => DiskFormat::Qcow2,
                "raw" => DiskFormat::Raw,
                "vmdk" => DiskFormat::Vmdk,
                "vdi" => DiskFormat::Vdi,
                other => DiskFormat::Other(other.to_string()),
            };
        }
    }

    // Fall back to extension-based detection if qemu-img fails or file doesn't exist
    path.extension()
        .and_then(|ext| ext.to_str())
        .map(DiskFormat::from_extension)
        .unwrap_or(DiskFormat::Raw)
}

/// Extract network configuration
fn extract_network(content: &str) -> Option<NetworkConfig> {
    let mut config = NetworkConfig::default();
    let mut has_network = false;

    for line in content.lines() {
        if line.trim_start().starts_with('#') {
            continue;
        }

        // Check for network model via -device
        if line.contains("-device") {
            // Extract network device model from -device lines
            if line.contains("virtio-net") {
                config.model = "virtio-net".to_string();
                has_network = true;
            } else if line.contains("e1000") && line.contains("netdev=") {
                config.model = "e1000".to_string();
                has_network = true;
            } else if line.contains("rtl8139") && line.contains("netdev=") {
                config.model = "rtl8139".to_string();
                has_network = true;
            }
        }

        // Check for network model via -net nic
        if line.contains("-net nic") || line.contains("-nic") {
            has_network = true;

            if line.contains("model=virtio") {
                config.model = "virtio-net".to_string();
            } else if line.contains("model=e1000") {
                config.model = "e1000".to_string();
            } else if line.contains("model=rtl8139") {
                config.model = "rtl8139".to_string();
            }
        }

        // Check for netdev backends
        if line.contains("-netdev") {
            has_network = true;

            if line.contains("passt") {
                config.backend = NetworkBackend::Passt;
                config.user_net = false;
            } else if line.contains("bridge") {
                config.user_net = false;
                // Extract bridge name
                if let Some(idx) = line.find("br=") {
                    let rest = &line[idx + 3..];
                    let bridge: String = rest
                        .chars()
                        .take_while(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
                        .collect();
                    config.backend = NetworkBackend::Bridge(bridge.clone());
                    config.bridge = Some(bridge);
                } else {
                    config.backend = NetworkBackend::Bridge("qemubr0".to_string());
                    config.bridge = Some("qemubr0".to_string());
                }
            } else if line.contains("user") {
                config.user_net = true;
                config.backend = NetworkBackend::User;

                // Extract port forwards from hostfwd
                config.port_forwards = extract_port_forwards(line);
            }
        }

        // Check for -net user/bridge (legacy format)
        if line.contains("-net user") {
            has_network = true;
            config.user_net = true;
            config.backend = NetworkBackend::User;
            config.port_forwards.extend(extract_port_forwards(line));
        }

        if line.contains("-net bridge") {
            has_network = true;
            config.user_net = false;
            if let Some(idx) = line.find("br=") {
                let rest = &line[idx + 3..];
                let bridge: String = rest
                    .chars()
                    .take_while(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
                    .collect();
                config.backend = NetworkBackend::Bridge(bridge.clone());
                config.bridge = Some(bridge);
            }
        }
    }

    if has_network || content.contains("-net") || content.contains("-nic") {
        Some(config)
    } else {
        None
    }
}

/// Extract port forwarding rules from a hostfwd string
fn extract_port_forwards(line: &str) -> Vec<PortForward> {
    let mut forwards = Vec::new();

    // Find each hostfwd= segment
    let mut search_from = 0;
    while let Some(idx) = line[search_from..].find("hostfwd=") {
        let start = search_from + idx + 8; // skip "hostfwd="
        let rest = &line[start..];

        // Format: protocol::hostport-:guestport
        // Or: protocol:addr:hostport-:guestport
        let segment: String = rest
            .chars()
            .take_while(|c| *c != ',' && !c.is_whitespace() && *c != '\\')
            .collect();

        if let Some(pf) = parse_hostfwd_segment(&segment) {
            forwards.push(pf);
        }

        search_from = start + segment.len();
    }

    forwards
}

/// Parse a single hostfwd segment like "tcp::2222-:22"
fn parse_hostfwd_segment(segment: &str) -> Option<PortForward> {
    // Split on the dash separator between host and guest
    let parts: Vec<&str> = segment.splitn(2, '-').collect();
    if parts.len() != 2 {
        return None;
    }

    let host_part = parts[0]; // "tcp::2222" or "tcp:addr:2222"
    let guest_part = parts[1]; // ":22" or ":addr:22"

    // Parse protocol from the beginning
    let protocol = if host_part.starts_with("udp") {
        PortProtocol::Udp
    } else {
        PortProtocol::Tcp
    };

    // Extract host port (last number in host_part after protocol)
    let host_port: u16 = host_part
        .rsplit(':')
        .next()?
        .parse()
        .ok()?;

    // Extract guest port (last number in guest_part)
    let guest_port: u16 = guest_part
        .rsplit(':')
        .next()?
        .parse()
        .ok()?;

    Some(PortForward {
        protocol,
        host_port,
        guest_port,
    })
}

/// Extract BIOS/ROM path from -bios argument
///
/// Parses lines like `-bios "$ROM"` and resolves shell variables.
/// Filters out OVMF/EFI paths (those are handled by UEFI detection).
fn extract_bios_path(content: &str, vm_dir: &Path) -> Option<PathBuf> {
    let vars = extract_shell_variables(content, vm_dir);

    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('#') {
            continue;
        }

        if let Some(idx) = trimmed.find("-bios ") {
            let rest = &trimmed[idx + 6..];
            let raw_path = if rest.starts_with('"') {
                // Quoted path like -bios "$ROM"
                let inner = &rest[1..];
                if let Some(end) = inner.find('"') {
                    inner[..end].to_string()
                } else {
                    inner.to_string()
                }
            } else {
                // Unquoted path
                rest.chars()
                    .take_while(|c| !c.is_whitespace() && *c != '\\')
                    .collect()
            };

            // Expand shell variables
            let expanded = expand_variables(&raw_path, &vars, vm_dir);
            let path = resolve_path(&expanded, vm_dir);

            // Filter out OVMF/EFI paths - those are UEFI firmware, not BIOS ROMs
            let path_str = path.to_string_lossy().to_lowercase();
            if path_str.contains("ovmf") || path_str.contains("efi") || path_str.contains("uefi") {
                continue;
            }

            return Some(path);
        }
    }
    None
}

/// Extract extra arguments we don't specifically handle
fn extract_extra_args(content: &str) -> Vec<String> {
    let mut args = Vec::new();

    // Look for display settings generically (handles gtk, sdl, vnc, spice-app, etc.)
    for line in content.lines() {
        if line.trim_start().starts_with('#') {
            continue;
        }
        if let Some(idx) = line.find("-display ") {
            let rest = &line[idx + 9..];
            // Extract the display backend (supports hyphenated names like spice-app)
            let backend: String = rest
                .chars()
                .take_while(|c| c.is_alphanumeric() || *c == '-')
                .collect();
            if !backend.is_empty() {
                args.push(format!("-display {}", backend));
                break;
            }
        }
    }

    // Look for USB
    if content.contains("-usb") {
        args.push("-usb".to_string());
    }

    // Look for RTC settings
    if content.contains("-rtc base=localtime") {
        args.push("-rtc base=localtime".to_string());
    }

    args
}

#[cfg(test)]
#[path = "tests/launch_parser.rs"]
mod tests;