xonecas.ioDon't click! Sean Caetano Martin Sign in
cast / src / vm / bake.rs 189 lines5.8 kB Raw
1use crate::app::bus::{Bus, Event};
2use crate::paths;
3use crate::vm::{download, files, qemu, seed};
4use std::io::{self, BufRead, BufReader, Write};
5use std::os::unix::fs::MetadataExt;
6use std::path::Path;
7use std::process::{Command, Stdio};
8
9const URL: &str =
10    "https://cloud.debian.org/images/cloud/trixie/latest/debian-13-generic-amd64.qcow2";
11const PROVISION: &str = include_str!("../../assets/provision.sh");
12
13pub const STAGES: [&str; 6] = [
14    "Download debian-13 cloud image",
15    "Install dev packages",
16    "Install claude, opencode, rust, go, node and agent-browser",
17    "Copy ~/.claude/CLAUDE.md + skills",
18    "Mount working folder and cast data (9p)",
19    "Set up the xfce desktop with autologin and no screen blanking",
20];
21
22#[derive(Clone)]
23pub enum Progress {
24    Stage(usize, u8),
25    Detail(String),
26    Done,
27    Failed(String),
28}
29
30pub fn start(bus: Bus, env: String) {
31    std::thread::spawn(move || {
32        let end = match bake(&bus, &env) {
33            Ok(()) => Progress::Done,
34            Err(e) => Progress::Failed(e.to_string()),
35        };
36        bus.send(Event::Bake(end));
37    });
38}
39
40pub fn skills() -> usize {
41    std::fs::read_dir(paths::home().join(".claude/skills")).map_or(0, |d| d.count())
42}
43
44fn bake(bus: &Bus, env: &str) -> io::Result<()> {
45    let send = |p| bus.send(Event::Bake(p));
46    std::fs::create_dir_all(paths::data())?;
47    let _ = std::fs::remove_file(files::baked_marker());
48    if !files::base().exists() {
49        download::fetch(URL, &files::base(), |p| send(Progress::Stage(0, p)))?;
50    }
51    send(Progress::Stage(0, 100));
52    let _ = std::fs::remove_file(files::disk());
53    run(Command::new("qemu-img")
54        .args(["create", "-q", "-f", "qcow2", "-F", "qcow2", "-b"])
55        .arg(files::base())
56        .arg(files::disk())
57        .arg("20G"))?;
58    if !files::key().exists() {
59        run(Command::new("ssh-keygen")
60            .args(["-q", "-t", "ed25519", "-N", "", "-C", "cast", "-f"])
61            .arg(files::key()))?;
62    }
63    stage(env)?;
64    let pubkey = std::fs::read_to_string(files::key().with_extension("pub"))?;
65    let iso = seed::write(
66        &paths::data(),
67        &pubkey,
68        std::fs::metadata(paths::home())?.uid(),
69    )?;
70    let mut child = qemu::command(&files::disk(), &[("stage", &files::stage(), true)])
71        .args([
72            "-nic",
73            "user,model=virtio-net-pci",
74            "-serial",
75            "null",
76            "-serial",
77            "stdio",
78            "-drive",
79        ])
80        .arg(format!("file={},media=cdrom", iso.display()))
81        .stdin(Stdio::null())
82        .stdout(Stdio::piped())
83        .stderr(Stdio::null())
84        .spawn()?;
85    let (mut done, mut failed) = (false, None);
86    let mut log = std::fs::File::create(files::console_log())?;
87    for line in BufReader::new(child.stdout.take().expect("piped"))
88        .lines()
89        .map_while(Result::ok)
90    {
91        let line = clean(&line);
92        let _ = writeln!(log, "{line}");
93        match line.find("CAST ").map(|i| line[i + 5..].trim().to_string()) {
94            Some(m) if m == "done" => done = true,
95            Some(m) if m.starts_with("fail") => failed = Some(m[4..].trim().to_string()),
96            Some(m) => {
97                let n: Vec<&str> = m.split_whitespace().collect();
98                if let [_, i, p] = n[..] {
99                    send(Progress::Stage(
100                        i.parse().unwrap_or(0),
101                        p.parse().unwrap_or(0),
102                    ));
103                }
104            }
105            None if !line.trim().is_empty() => send(Progress::Detail(line)),
106            None => {}
107        }
108    }
109    child.wait()?;
110    let _ = std::fs::remove_dir_all(files::stage());
111    match (failed, done) {
112        (Some(f), _) => Err(io::Error::other(f)),
113        (None, false) => Err(io::Error::other(format!(
114            "the VM shut down before provisioning finished, see {}",
115            crate::paths::tilde(&files::console_log())
116        ))),
117        (None, true) => std::fs::write(files::baked_marker(), ""),
118    }
119}
120
121fn stage(env: &str) -> io::Result<()> {
122    let dir = files::stage();
123    let _ = std::fs::remove_dir_all(&dir);
124    std::fs::create_dir_all(dir.join("claude"))?;
125    std::fs::write(dir.join("provision.sh"), PROVISION)?;
126    std::fs::write(dir.join("env"), env)?;
127    let claude = paths::home().join(".claude");
128    if claude.join("CLAUDE.md").exists() {
129        std::fs::copy(claude.join("CLAUDE.md"), dir.join("claude/CLAUDE.md"))?;
130    }
131    copy_dir(&claude.join("skills"), &dir.join("claude/skills"))
132}
133
134fn copy_dir(from: &Path, to: &Path) -> io::Result<()> {
135    let Ok(entries) = std::fs::read_dir(from) else {
136        return Ok(());
137    };
138    std::fs::create_dir_all(to)?;
139    for e in entries.flatten() {
140        let (src, dst) = (e.path(), to.join(e.file_name()));
141        if src.is_dir() {
142            copy_dir(&src, &dst)?
143        } else {
144            std::fs::copy(&src, &dst).map(|_| ())?
145        }
146    }
147    Ok(())
148}
149
150fn run(cmd: &mut Command) -> io::Result<()> {
151    let out = cmd.output()?;
152    if out.status.success() {
153        Ok(())
154    } else {
155        Err(io::Error::other(
156            String::from_utf8_lossy(&out.stderr).trim().to_string(),
157        ))
158    }
159}
160
161fn clean(line: &str) -> String {
162    let mut out = String::new();
163    let mut chars = line.chars();
164    while let Some(c) = chars.next() {
165        match c {
166            '\x1b' => {
167                for c in chars.by_ref() {
168                    if c.is_ascii_alphabetic() {
169                        break;
170                    }
171                }
172            }
173            c if c.is_control() => {}
174            c => out.push(c),
175        }
176    }
177    out
178}
179
180#[cfg(test)]
181mod tests {
182    #[test]
183    fn clean_strips_ansi_and_carriage_returns() {
184        assert_eq!(
185            super::clean("\x1b[0;32m  OK  \x1b[0m Started\r"),
186            "  OK   Started"
187        );
188    }
189}