aev-vm 0.1.0

Manage QEMU virtual machines in Rust and open their consoles in Aen
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
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
use std::net::Ipv4Addr;
use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;

use anyhow::{Context, Result, bail};
use clap::{CommandFactory, Parser, Subcommand};
use std::io::{self, IsTerminal};

use crate::aen_window;
use crate::config::{
    Acceleration, AudioMode, Firmware, NetworkMode, NetworkProtocol, PointerDevice, PortForward,
    UsbHostDevice,
};
use crate::console;
use crate::manager::{ConfigureOptions, CreateOptions, VmManager, VmStatus};
use crate::qemu::HostCapabilities;
use crate::qga::ShutdownMode;

#[derive(Debug, Parser)]
#[command(name = "aev-vm", version, about)]
struct Cli {
    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Check host virtualization, firmware, and display prerequisites.
    Doctor,
    /// Create a VM definition and qcow2 system disk.
    Init {
        /// Filesystem-safe VM name.
        name: String,
        /// Virtual system disk size.
        #[arg(long, default_value = "64G")]
        disk_size: String,
        /// Bootable installation ISO.
        #[arg(long)]
        iso: Option<PathBuf>,
        /// Guest RAM in MiB.
        #[arg(long, default_value_t = 4096)]
        memory: u64,
        /// Number of virtual CPUs.
        #[arg(long, default_value_t = 4)]
        cpus: u16,
        /// Guest boot firmware.
        #[arg(long, value_enum, default_value_t = FirmwareOption::Uefi)]
        firmware: FirmwareOption,
        /// Attach a persistent software TPM 2.0 (requires swtpm).
        #[arg(long)]
        tpm2: bool,
    },
    /// Create an independent full-copy clone of a stopped VM.
    Clone {
        /// Existing stopped VM.
        source: String,
        /// New VM name.
        destination: String,
    },
    /// Manage offline installation media.
    Media {
        name: String,
        #[command(subcommand)]
        action: MediaCommand,
    },
    /// Inspect or grow the system disk while a VM is stopped.
    Disk {
        name: String,
        #[command(subcommand)]
        action: DiskCommand,
    },
    /// Manage localhost user-network port forwarding.
    Port {
        name: String,
        #[command(subcommand)]
        action: PortCommand,
    },
    /// Manage host USB devices cold-plugged into a VM.
    Usb {
        name: String,
        #[command(subcommand)]
        action: UsbCommand,
    },
    /// Manage host directories exposed through virtio-9p.
    Share {
        name: String,
        #[command(subcommand)]
        action: ShareCommand,
    },
    /// Create, verify, or restore portable VM backups.
    Backup {
        #[command(subcommand)]
        action: BackupCommand,
    },
    /// Permanently delete a stopped VM and its managed storage.
    Delete {
        name: String,
        /// Confirm permanent deletion.
        #[arg(long)]
        yes: bool,
    },
    /// Change compute, firmware, network, audio, or pointer settings while stopped.
    Configure {
        name: String,
        /// Guest RAM in MiB.
        #[arg(long)]
        memory: Option<u64>,
        /// Number of virtual CPUs.
        #[arg(long)]
        cpus: Option<u16>,
        /// Virtualization accelerator preference.
        #[arg(long, value_enum)]
        acceleration: Option<AccelerationOption>,
        /// Guest network attachment.
        #[arg(long, value_enum)]
        network: Option<NetworkOption>,
        /// Host audio backend.
        #[arg(long, value_enum)]
        audio: Option<AudioOption>,
        /// Guest pointer device.
        #[arg(long, value_enum)]
        pointer_device: Option<PointerDeviceOption>,
        /// Guest boot firmware.
        #[arg(long, value_enum)]
        firmware: Option<FirmwareOption>,
    },
    /// Inspect or regenerate the VM Generation ID.
    Identity {
        name: String,
        #[command(subcommand)]
        action: IdentityCommand,
    },
    /// Inspect or adjust a running VM's virtio memory balloon.
    Balloon {
        name: String,
        #[command(subcommand)]
        action: BalloonCommand,
    },
    /// Capture a running VM's framebuffer as a new PPM file.
    Screenshot { name: String, destination: PathBuf },
    /// Start a VM in the background.
    Start { name: String },
    /// Start a VM if needed and open its native Aen console.
    Run {
        name: String,
        /// UNSAFE: allow paste without an atomic focus fence on final guest delivery.
        #[arg(long)]
        unsafe_unfenced_host_clipboard_paste: bool,
    },
    /// Open the native Aen console for a running VM.
    Console {
        name: String,
        /// UNSAFE: allow paste without an atomic focus fence on final guest delivery.
        #[arg(long)]
        unsafe_unfenced_host_clipboard_paste: bool,
    },
    /// Ask the guest to shut down, then stop QEMU after a timeout.
    Stop {
        name: String,
        #[arg(long, default_value_t = 30)]
        timeout: u64,
    },
    /// Stop QEMU immediately through QMP.
    Kill { name: String },
    /// Pause all virtual CPUs.
    Pause { name: String },
    /// Resume all virtual CPUs.
    Resume { name: String },
    /// Reset the guest machine.
    Reset { name: String },
    /// Communicate with the QEMU Guest Agent installed inside a VM.
    Agent {
        name: String,
        #[command(subcommand)]
        action: AgentCommand,
    },
    /// Manage offline internal qcow2 snapshots.
    Snapshot {
        name: String,
        #[command(subcommand)]
        action: SnapshotCommand,
    },
    /// Show a VM's current QMP state.
    Status { name: String },
    /// List all VM definitions.
    List,
    /// Print the exact argument-safe QEMU launch command.
    #[command(name = "command")]
    ShowQemu { name: String },
}

#[derive(Debug, Subcommand)]
enum SnapshotCommand {
    /// List snapshots.
    List,
    /// Save current disk state.
    Create { snapshot: String },
    /// Restore disk state.
    Revert { snapshot: String },
    /// Remove a snapshot.
    Delete { snapshot: String },
}

#[derive(Debug, Subcommand)]
enum AgentCommand {
    /// Verify that the guest agent is responsive.
    Ping,
    /// Print guest-agent version and supported commands as JSON.
    Info,
    /// Request a guest-agent power action.
    Shutdown {
        #[arg(value_enum, default_value_t = AgentShutdownMode::Powerdown)]
        mode: AgentShutdownMode,
    },
}

#[derive(Debug, Subcommand)]
enum MediaCommand {
    /// Print currently attached installation media.
    Show,
    /// Attach a read-only ISO or raw optical image.
    Attach { path: PathBuf },
    /// Detach installation media.
    Detach,
}

#[derive(Debug, Subcommand)]
enum DiskCommand {
    /// Print system-disk information as JSON.
    Info,
    /// Increase virtual disk capacity by an amount such as 20G.
    Grow { amount: String },
}

#[derive(Debug, Subcommand)]
enum PortCommand {
    /// List configured forwards.
    List,
    /// Add a forward that becomes active on the next VM start.
    Add {
        #[arg(long, value_enum, default_value_t = PortProtocol::Tcp)]
        protocol: PortProtocol,
        #[arg(long, default_value_t = Ipv4Addr::LOCALHOST)]
        host_address: Ipv4Addr,
        #[arg(long)]
        host_port: u16,
        #[arg(long)]
        guest_port: u16,
    },
    /// Remove a forward by its host listener.
    Remove {
        #[arg(long, value_enum, default_value_t = PortProtocol::Tcp)]
        protocol: PortProtocol,
        #[arg(long, default_value_t = Ipv4Addr::LOCALHOST)]
        host_address: Ipv4Addr,
        #[arg(long)]
        host_port: u16,
    },
}

#[derive(Debug, Subcommand)]
enum UsbCommand {
    /// List configured host USB bus and address pairs.
    List,
    /// Add a host device that becomes active on the next VM start.
    Add {
        #[arg(long)]
        bus: u16,
        #[arg(long)]
        address: u16,
    },
    /// Remove a host device while the VM is stopped.
    Remove {
        #[arg(long)]
        bus: u16,
        #[arg(long)]
        address: u16,
    },
}

#[derive(Debug, Subcommand)]
enum ShareCommand {
    /// List configured host directory shares.
    List,
    /// Add a read-only share, or explicitly allow writes.
    Add {
        tag: String,
        path: PathBuf,
        #[arg(long)]
        writable: bool,
    },
    /// Remove a share by its guest mount tag.
    Remove { tag: String },
}

#[derive(Debug, Subcommand)]
enum BackupCommand {
    /// Create a new portable backup directory from a stopped VM.
    Create { name: String, destination: PathBuf },
    /// Verify manifest hashes and qcow2 structure.
    Verify { path: PathBuf },
    /// Restore a verified backup under a new VM name.
    Restore { path: PathBuf, name: String },
}

#[derive(Debug, Subcommand)]
enum IdentityCommand {
    /// Print the current stable VM Generation ID.
    Show,
    /// Generate a new ID while the VM is stopped.
    Regenerate,
}

#[derive(Debug, Subcommand)]
enum BalloonCommand {
    /// Show guest-reported runtime memory and the configured maximum.
    Show,
    /// Request a runtime memory target in MiB.
    Set { memory_mib: u64 },
    /// Return the target to the configured boot memory.
    Restore,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum PortProtocol {
    Tcp,
    Udp,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum AccelerationOption {
    Auto,
    Kvm,
    Tcg,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum FirmwareOption {
    Uefi,
    UefiSecure,
    Bios,
}

impl From<FirmwareOption> for Firmware {
    fn from(value: FirmwareOption) -> Self {
        match value {
            FirmwareOption::Uefi => Self::Uefi,
            FirmwareOption::UefiSecure => Self::UefiSecure,
            FirmwareOption::Bios => Self::Bios,
        }
    }
}

impl From<AccelerationOption> for Acceleration {
    fn from(value: AccelerationOption) -> Self {
        match value {
            AccelerationOption::Auto => Self::Auto,
            AccelerationOption::Kvm => Self::Kvm,
            AccelerationOption::Tcg => Self::Tcg,
        }
    }
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum NetworkOption {
    User,
    None,
}

impl From<NetworkOption> for NetworkMode {
    fn from(value: NetworkOption) -> Self {
        match value {
            NetworkOption::User => Self::User,
            NetworkOption::None => Self::None,
        }
    }
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum AudioOption {
    None,
    Pipewire,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum PointerDeviceOption {
    Tablet,
    Mouse,
}

impl From<PointerDeviceOption> for PointerDevice {
    fn from(value: PointerDeviceOption) -> Self {
        match value {
            PointerDeviceOption::Tablet => Self::Tablet,
            PointerDeviceOption::Mouse => Self::Mouse,
        }
    }
}

impl From<AudioOption> for AudioMode {
    fn from(value: AudioOption) -> Self {
        match value {
            AudioOption::None => Self::None,
            AudioOption::Pipewire => Self::Pipewire,
        }
    }
}

impl From<PortProtocol> for NetworkProtocol {
    fn from(protocol: PortProtocol) -> Self {
        match protocol {
            PortProtocol::Tcp => Self::Tcp,
            PortProtocol::Udp => Self::Udp,
        }
    }
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum AgentShutdownMode {
    Powerdown,
    Halt,
    Reboot,
}

impl From<AgentShutdownMode> for ShutdownMode {
    fn from(mode: AgentShutdownMode) -> Self {
        match mode {
            AgentShutdownMode::Powerdown => Self::Powerdown,
            AgentShutdownMode::Halt => Self::Halt,
            AgentShutdownMode::Reboot => Self::Reboot,
        }
    }
}

/// Run the Aev VM command line and return its exit status.
#[must_use]
pub fn main() -> ExitCode {
    match run() {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("aev-vm: {error:#}");
            ExitCode::FAILURE
        }
    }
}

fn run() -> Result<()> {
    let cli = Cli::parse();
    let Some(command) = cli.command else {
        if io::stdin().is_terminal() && io::stdout().is_terminal() {
            return crate::vm_menu::run(&VmManager::discover()?);
        }
        Cli::command().print_help()?;
        println!();
        return Ok(());
    };
    if matches!(command, Command::Doctor) {
        return doctor();
    }
    let manager = VmManager::discover()?;
    match command {
        Command::Doctor => unreachable!(),
        Command::Init {
            name,
            disk_size,
            iso,
            memory,
            cpus,
            firmware,
            tpm2,
        } => {
            let path = manager.create(&CreateOptions {
                name,
                disk_size,
                install_media: iso,
                memory_mib: memory,
                vcpus: cpus,
                firmware: firmware.into(),
                software_tpm2: tpm2,
            })?;
            println!("created {}", path.display());
        }
        Command::Clone {
            source,
            destination,
        } => {
            let path = manager.clone_vm(&source, &destination)?;
            println!("cloned {source} to {destination} at {}", path.display());
        }
        Command::Media { name, action } => match action {
            MediaCommand::Show => match manager.config(&name)?.install_media {
                Some(media) => println!("{}", media.display()),
                None => println!("none"),
            },
            MediaCommand::Attach { path } => {
                let media = manager.media_attach(&name, &path)?;
                println!("attached {} to {name}", media.display());
            }
            MediaCommand::Detach => match manager.media_detach(&name)? {
                Some(media) => println!("detached {} from {name}", media.display()),
                None => println!("{name} had no installation media attached"),
            },
        },
        Command::Disk { name, action } => match action {
            DiskCommand::Info => {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&manager.disk_info(&name)?)?
                );
            }
            DiskCommand::Grow { amount } => {
                manager.disk_grow(&name, &amount)?;
                println!("grew {name} system disk by {amount}");
            }
        },
        Command::Port { name, action } => match action {
            PortCommand::List => {
                for forward in manager.config(&name)?.network.forwards {
                    println!(
                        "{} {}:{} -> guest:{}",
                        forward.protocol.qemu_name(),
                        forward.host_address,
                        forward.host_port,
                        forward.guest_port
                    );
                }
            }
            PortCommand::Add {
                protocol,
                host_address,
                host_port,
                guest_port,
            } => {
                manager.port_add(
                    &name,
                    PortForward {
                        protocol: protocol.into(),
                        host_address,
                        host_port,
                        guest_port,
                    },
                )?;
                println!("added {host_address}:{host_port} -> guest:{guest_port} for {name}");
            }
            PortCommand::Remove {
                protocol,
                host_address,
                host_port,
            } => {
                let removed =
                    manager.port_remove(&name, protocol.into(), host_address, host_port)?;
                println!(
                    "removed {} {}:{} -> guest:{} from {name}",
                    removed.protocol.qemu_name(),
                    removed.host_address,
                    removed.host_port,
                    removed.guest_port
                );
            }
        },
        Command::Usb { name, action } => match action {
            UsbCommand::List => {
                let mut devices = manager.config(&name)?.usb_devices;
                devices.sort_unstable_by_key(|device| (device.bus, device.address));
                for device in devices {
                    println!("bus {:03} address {:03}", device.bus, device.address);
                }
            }
            UsbCommand::Add { bus, address } => {
                manager.usb_add(&name, UsbHostDevice { bus, address })?;
                println!("assigned USB bus {bus:03} address {address:03} to {name}");
            }
            UsbCommand::Remove { bus, address } => {
                manager.usb_remove(&name, UsbHostDevice { bus, address })?;
                println!("removed USB bus {bus:03} address {address:03} from {name}");
            }
        },
        Command::Share { name, action } => match action {
            ShareCommand::List => {
                let mut shares = manager.config(&name)?.shares;
                shares.sort_unstable_by(|left, right| left.tag.cmp(&right.tag));
                for share in shares {
                    println!(
                        "{}\t{}\t{}",
                        share.tag,
                        if share.read_only {
                            "read-only"
                        } else {
                            "writable"
                        },
                        share.path.display()
                    );
                }
            }
            ShareCommand::Add {
                tag,
                path,
                writable,
            } => {
                let share = manager.share_add(&name, tag, &path, !writable)?;
                println!(
                    "shared {} as {} ({}) for {name}",
                    share.path.display(),
                    share.tag,
                    if share.read_only {
                        "read-only"
                    } else {
                        "writable"
                    }
                );
            }
            ShareCommand::Remove { tag } => {
                let share = manager.share_remove(&name, &tag)?;
                println!("removed share {} from {name}", share.tag);
            }
        },
        Command::Backup { action } => match action {
            BackupCommand::Create { name, destination } => {
                let manifest = manager.backup_create(&name, &destination)?;
                println!(
                    "created verified backup of {} at {} ({})",
                    manifest.source_name,
                    destination.display(),
                    manifest.disk.sha256
                );
            }
            BackupCommand::Verify { path } => {
                let manifest = manager.backup_verify(&path)?;
                println!(
                    "verified backup of {} from Unix time {}",
                    manifest.source_name, manifest.created_at_unix
                );
            }
            BackupCommand::Restore { path, name } => {
                let definition = manager.backup_restore(&path, &name)?;
                println!("restored {name} at {}", definition.display());
            }
        },
        Command::Delete { name, yes } => {
            if !yes {
                bail!("refusing to delete {name} without --yes");
            }
            let report = manager.delete_vm(&name)?;
            println!("deleted {}", report.definition.display());
            if let Some(disk) = report.preserved_disk {
                println!("preserved external disk {}", disk.display());
            }
        }
        Command::Configure {
            name,
            memory,
            cpus,
            acceleration,
            network,
            audio,
            pointer_device,
            firmware,
        } => {
            let config = manager.configure(
                &name,
                &ConfigureOptions {
                    memory_mib: memory,
                    vcpus: cpus,
                    acceleration: acceleration.map(Into::into),
                    network_mode: network.map(Into::into),
                    audio: audio.map(Into::into),
                    pointer_device: pointer_device.map(Into::into),
                    firmware: firmware.map(Into::into),
                },
            )?;
            println!(
                "configured {name}: {} MiB, {} vCPUs, {:?}, firmware {:?}, network {:?}, audio {:?}, pointer {:?}",
                config.memory_mib,
                config.vcpus,
                config.acceleration,
                config.firmware,
                config.network.mode,
                config.audio,
                config.pointer_device
            );
        }
        Command::Identity { name, action } => match action {
            IdentityCommand::Show => match manager.generation_id(&name)? {
                Some(generation_id) => println!("{generation_id}"),
                None => println!("auto"),
            },
            IdentityCommand::Regenerate => {
                println!("{}", manager.regenerate_generation_id(&name)?);
            }
        },
        Command::Balloon { name, action } => match action {
            BalloonCommand::Show => {
                let status = manager.balloon_status(&name)?;
                println!(
                    "actual {} bytes, configured maximum {} MiB",
                    status.actual_bytes, status.configured_mib
                );
            }
            BalloonCommand::Set { memory_mib } => {
                manager.balloon_set(&name, memory_mib)?;
                println!("requested {memory_mib} MiB for {name}");
            }
            BalloonCommand::Restore => {
                let configured_mib = manager.balloon_restore(&name)?;
                println!("restored {name} target to {configured_mib} MiB");
            }
        },
        Command::Screenshot { name, destination } => {
            let bytes = manager.screenshot(&name, &destination)?;
            println!(
                "captured {name} to {} ({bytes} bytes)",
                destination.display()
            );
        }
        Command::Start { name } => {
            let state = manager.start(&name)?;
            println!("started {} as PID {}", state.name, state.pid);
        }
        Command::Run {
            name,
            unsafe_unfenced_host_clipboard_paste,
        } => open_vm(&manager, &name, unsafe_unfenced_host_clipboard_paste)?,
        Command::Console {
            name,
            unsafe_unfenced_host_clipboard_paste,
        } => {
            let state = manager.running_state(&name)?;
            if unsafe_unfenced_host_clipboard_paste {
                console::run_with_unfenced_host_clipboard_paste(&name, &state.display_socket)?;
            } else {
                console::run(&name, &state.display_socket)?;
            }
        }
        Command::Stop { name, timeout } => {
            manager.stop(&name, Duration::from_secs(timeout))?;
            println!("stopped {name}");
        }
        Command::Kill { name } => {
            manager.kill(&name)?;
            println!("stopped {name}");
        }
        Command::Pause { name } => {
            manager.pause(&name)?;
            println!("paused {name}");
        }
        Command::Resume { name } => {
            manager.resume(&name)?;
            println!("resumed {name}");
        }
        Command::Reset { name } => {
            manager.reset(&name)?;
            println!("reset {name}");
        }
        Command::Agent { name, action } => match action {
            AgentCommand::Ping => {
                manager.agent_ping(&name)?;
                println!("guest agent is ready for {name}");
            }
            AgentCommand::Info => {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&manager.agent_info(&name)?)?
                );
            }
            AgentCommand::Shutdown { mode } => {
                manager.agent_shutdown(&name, mode.into())?;
                println!("sent guest-agent {mode:?} request to {name}");
            }
        },
        Command::Snapshot { name, action } => match action {
            SnapshotCommand::List => print!("{}", manager.snapshot_list(&name)?),
            SnapshotCommand::Create { snapshot } => {
                manager.snapshot_create(&name, &snapshot)?;
                println!("created snapshot {snapshot} for {name}");
            }
            SnapshotCommand::Revert { snapshot } => {
                manager.snapshot_revert(&name, &snapshot)?;
                println!("reverted {name} to snapshot {snapshot}");
            }
            SnapshotCommand::Delete { snapshot } => {
                manager.snapshot_delete(&name, &snapshot)?;
                println!("deleted snapshot {snapshot} from {name}");
            }
        },
        Command::Status { name } => match manager.status(&name)? {
            VmStatus::Stopped => println!("{name}: stopped"),
            VmStatus::Running { pid, qemu_status } => {
                println!("{name}: {qemu_status} (PID {pid})");
            }
            VmStatus::Stale { pid } => println!("{name}: stale state (PID {pid})"),
        },
        Command::List => {
            for name in manager.list()? {
                let status = match manager.status(&name)? {
                    VmStatus::Stopped => "stopped".to_owned(),
                    VmStatus::Running { qemu_status, .. } => qemu_status,
                    VmStatus::Stale { .. } => "stale".to_owned(),
                };
                println!("{name}\t{status}");
            }
        }
        Command::ShowQemu { name } => println!("{}", manager.command(&name)?.display()),
    }
    Ok(())
}

pub(crate) fn open_vm(
    manager: &VmManager,
    name: &str,
    unsafe_unfenced_host_clipboard_paste: bool,
) -> Result<()> {
    let native_socket = console::preflight_native_endpoint()?;
    if !matches!(manager.status(name)?, VmStatus::Running { .. }) {
        let state = manager.start(name)?;
        println!("started {} as PID {}", state.name, state.pid);
    }
    let state = manager.running_state(name)?;
    if unsafe_unfenced_host_clipboard_paste {
        console::run_with_unfenced_endpoint(name, &state.display_socket, &native_socket)
    } else {
        console::run_with_endpoint(name, &state.display_socket, &native_socket)
    }
}

fn doctor() -> Result<()> {
    let host = HostCapabilities::probe()?;
    println!("qemu: {}", host.qemu.display());
    println!("qemu-img: {}", host.qemu_img.display());
    println!(
        "kvm: {}",
        if host.kvm_available {
            "available"
        } else {
            "unavailable; auto mode will use TCG"
        }
    );
    println!(
        "uefi-code: {}",
        host.uefi_code
            .as_deref()
            .map_or_else(|| "not found".to_owned(), |path| path.display().to_string())
    );
    println!(
        "uefi-secure-code: {}",
        host.uefi_secure_code
            .as_deref()
            .map_or_else(|| "not found".to_owned(), |path| path.display().to_string())
    );
    println!(
        "uefi-secure-vars: {}",
        host.uefi_secure_vars
            .as_deref()
            .map_or_else(|| "not found".to_owned(), |path| path.display().to_string())
    );
    println!(
        "uefi-vars: {}",
        host.uefi_vars
            .as_deref()
            .map_or_else(|| "not found".to_owned(), |path| path.display().to_string())
    );
    let socket = aen_window::socket_from_env()
        .context("start an Aen session or set AEN_WINDOW_SOCKET before opening a console")?;
    console::probe(&socket)?;
    println!("aen-window-socket: {}", socket.display());
    println!("aen-window-connection: ready (native configure verified)");
    Ok(())
}

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

    fn paste_opt_in(command: &Command) -> bool {
        match command {
            Command::Run {
                unsafe_unfenced_host_clipboard_paste,
                ..
            }
            | Command::Console {
                unsafe_unfenced_host_clipboard_paste,
                ..
            } => *unsafe_unfenced_host_clipboard_paste,
            _ => panic!("expected run or console command"),
        }
    }

    #[test]
    fn unsafe_unfenced_clipboard_flag_is_explicit_for_run_and_console() {
        for subcommand in ["run", "console"] {
            let safe = Cli::try_parse_from(["knottvm", subcommand, "guest"]).unwrap();
            assert!(!paste_opt_in(safe.command.as_ref().unwrap()));

            let unsafe_opt_in = Cli::try_parse_from([
                "knottvm",
                subcommand,
                "guest",
                "--unsafe-unfenced-host-clipboard-paste",
            ])
            .unwrap();
            assert!(paste_opt_in(unsafe_opt_in.command.as_ref().unwrap()));

            let help = Cli::try_parse_from(["knottvm", subcommand, "guest", "--help"]).unwrap_err();
            assert_eq!(help.kind(), clap::error::ErrorKind::DisplayHelp);
            assert!(help.to_string().contains("UNSAFE"));
            assert!(help.to_string().contains("final guest delivery"));
        }
    }
}