windows_headless/
storage.rs1use anyhow::{Context, Result};
2use std::path::{Path, PathBuf};
3use tokio::process::Command;
4
5pub struct DiskManager;
7
8impl DiskManager {
9 pub async fn create_base(qemu_img: &Path, path: &Path, size_gb: u32) -> Result<()> {
13 let status = Command::new(qemu_img)
14 .arg("create")
15 .arg("-f")
16 .arg("qcow2")
17 .arg(path)
18 .arg(format!("{size_gb}G"))
19 .status()
20 .await
21 .context("failed to execute qemu-img (is qemu-utils installed?)")?;
22 if !status.success() {
23 anyhow::bail!("qemu-img create base failed for {}", path.display());
24 }
25 Ok(())
26 }
27
28 pub async fn create_overlay(qemu_img: &Path, base: &Path, overlay: &Path) -> Result<()> {
31 let status = Command::new(qemu_img)
32 .arg("create")
33 .arg("-f")
34 .arg("qcow2")
35 .arg("-F")
36 .arg("qcow2")
37 .arg("-b")
38 .arg(base)
39 .arg(overlay)
40 .status()
41 .await
42 .context("failed to execute qemu-img")?;
43 if !status.success() {
44 anyhow::bail!(
45 "qemu-img failed to create overlay {} over {}",
46 overlay.display(),
47 base.display()
48 );
49 }
50 Ok(())
51 }
52
53 pub fn ensure_unattend_dir(dir: &Path, xml: &str) -> Result<PathBuf> {
56 std::fs::create_dir_all(dir).with_context(|| format!("mkdir {}", dir.display()))?;
57 let file = dir.join(crate::paths::UNATTEND_XML);
58 std::fs::write(&file, xml).with_context(|| format!("write {}", file.display()))?;
59 Ok(file)
60 }
61
62 pub async fn build_unattend_iso(xml_path: &Path, out_iso: &Path) -> Result<()> {
64 let mkisofs = if which("mkisofs") {
65 "mkisofs"
66 } else if which("genisoimage") {
67 "genisoimage"
68 } else if which("xorriso") {
69 "xorriso"
70 } else {
71 anyhow::bail!(
72 "no mkisofs/genisoimage/xorriso on PATH (needed only for --unattend-iso)"
73 );
74 };
75 let mut cmd = Command::new(mkisofs);
76 if mkisofs == "xorriso" {
77 cmd.arg("-as").arg("mkisofs");
78 }
79 let status = cmd
80 .arg("-o")
81 .arg(out_iso)
82 .arg("-J")
83 .arg("-r")
84 .arg(xml_path)
85 .status()
86 .await
87 .context("failed to execute ISO tool")?;
88 if !status.success() {
89 anyhow::bail!("ISO authoring failed");
90 }
91 Ok(())
92 }
93}
94
95fn which(bin: &str) -> bool {
96 std::process::Command::new("which")
97 .arg(bin)
98 .output()
99 .map(|o| o.status.success())
100 .unwrap_or(false)
101}
102
103#[cfg(test)]
104mod tests {
105 use super::*;
106
107 #[test]
108 fn unattend_staging_writes_root_file() {
109 let dir = tempfile::tempdir().unwrap();
110 let target = dir.path().join("unattend");
111 let f = DiskManager::ensure_unattend_dir(&target, "<unattend/>").unwrap();
112 assert_eq!(f, target.join("autounattend.xml"));
113 assert_eq!(std::fs::read_to_string(f).unwrap(), "<unattend/>");
114 }
115}