helix-toolbox 1.12.2

Build, configure and optimize a Linux machine from a terminal menu: installs, dotfiles, updates, backups and health checks, every change planned and confirmed first.
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
//! `helix-toolbox bundle`: make an offline installation bundle, check one, and
//! install from one.

use anyhow::{Context, Result, bail};
use clap::Subcommand;
use helix_toolbox_catalog::Catalog;
use helix_toolbox_core::printable;
use helix_toolbox_engine::{bundle, doctor, history};
use helix_toolbox_platform::LinuxInfo;
use std::{path::Path, path::PathBuf, process::Command};

#[derive(Subcommand)]
pub enum BundleCommand {
    /// Download the packages entries need, with Helix Toolbox itself, into a new
    /// folder, for a machine of this distribution without reliable internet;
    /// Flatpak applications installed here are copied with their runtimes
    /// (flatpak create-usb). Nothing is installed here.
    Create {
        /// The folder to make; it must be new or empty.
        directory: PathBuf,
        /// The entries (or profiles) to bundle.
        #[arg(required = true)]
        ids: Vec<String>,
        /// Every dependency, not only those this machine lacks: larger, for a
        /// machine set up less than this one.
        #[arg(long)]
        complete: bool,
        /// Show what would be downloaded and stop.
        #[arg(long)]
        dry_run: bool,
    },
    /// Check a bundle: made for this distribution and architecture, and every
    /// file matching its checksum.
    Verify { directory: PathBuf },
    /// Check a bundle, then install its packages from its files, after
    /// confirmation. A bundle installs as a whole: its
    /// entries share their dependencies.
    Install {
        directory: PathBuf,
        /// Install Debian packages this machine's repository index does not
        /// know, and add a Flatpak remote this machine lacks with the
        /// bundle's copy of its key, on the bundle's word: only for a bundle
        /// you made yourself.
        #[arg(long)]
        trust_bundle: bool,
        /// Show the plan and stop.
        #[arg(long)]
        dry_run: bool,
        /// Skip the confirmation phrase, for deliberate automation.
        #[arg(long)]
        yes: bool,
    },
}

fn curl(url: &str, to: &Path) -> bool {
    // Package files are checked by their signatures or the repository's
    // signed index, so plain HTTP mirrors are allowed for them.
    Command::new("curl")
        .args([
            "--fail",
            "--location",
            "--silent",
            "--show-error",
            "--proto",
            "=https,http",
            "--output",
        ])
        .arg(to)
        .arg(url)
        .status()
        .is_ok_and(|status| status.success())
}

/// `flatpak create-usb`: the refs, with the runtimes they need, into the
/// bundle's Flatpak folder. From the system installation it first updates
/// that installation's summary, which needs root: through sudo, and the
/// copy is then given back to you.
fn create_usb(refs: &[String], user: bool, bundle: &Path) -> bool {
    let elevate = !user && !nix::unistd::geteuid().is_root();
    let mut command = if elevate {
        println!(
            "flatpak create-usb updates the system installation's summary first, which needs root; sudo may ask for your password."
        );
        let mut command = Command::new("sudo");
        command.arg("flatpak");
        command
    } else {
        Command::new("flatpak")
    };
    command
        .arg("create-usb")
        .arg(if user { "--user" } else { "--system" })
        // Locale extensions are installed in part, for your languages.
        .arg("--allow-partial")
        .arg(format!("--destination-repo={}", bundle::FLATPAKS))
        .arg(bundle)
        .args(refs);
    if !command.status().is_ok_and(|status| status.success()) {
        return false;
    }
    !elevate
        || Command::new("sudo")
            .arg("chown")
            .arg("-R")
            .arg(format!(
                "{}:{}",
                nix::unistd::getuid(),
                nix::unistd::getgid()
            ))
            .arg("--")
            .arg(bundle.join(bundle::FLATPAKS))
            .status()
            .is_ok_and(|status| status.success())
}

/// Where flatpak keeps a remote's signing key.
fn flatpak_key(remote: &str, user: bool) -> PathBuf {
    let variable = |name: &str| std::env::var_os(name).filter(|value| !value.is_empty());
    let installation = if user {
        variable("FLATPAK_USER_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|| {
                variable("XDG_DATA_HOME")
                    .map(PathBuf::from)
                    .or_else(|| {
                        variable("HOME").map(|home| PathBuf::from(home).join(".local/share"))
                    })
                    .unwrap_or_default()
                    .join("flatpak")
            })
    } else {
        variable("FLATPAK_SYSTEM_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from("/var/lib/flatpak"))
    };
    installation.join(format!("repo/{remote}.trustedkeys.gpg"))
}

/// The bytes in a folder and everything under it.
fn folder_bytes(path: &Path) -> u64 {
    let Ok(listing) = std::fs::read_dir(path) else {
        return 0;
    };
    listing
        .flatten()
        .map(|item| match item.file_type() {
            Ok(kind) if kind.is_dir() => folder_bytes(&item.path()),
            Ok(kind) if kind.is_file() => item.metadata().map(|data| data.len()).unwrap_or(0),
            _ => 0,
        })
        .sum()
}

/// zypper downloads as you, not as root, into a scratch root of its own
/// that shares this machine's repositories: with an empty package database
/// it takes every dependency, with this machine's own only those it lacks.
/// Each package is checked against the repository's signed metadata as it
/// downloads.
fn zypper_download(names: &[String], complete: bool, into: &Path) -> bool {
    let Ok(scratch) = bundle::scratch() else {
        return false;
    };
    let root = scratch.join("root");
    let cache = scratch.join("packages");
    let prepared = if complete {
        std::fs::create_dir_all(&root).is_ok()
    } else {
        Command::new("rpm")
            .args(["--eval", "%_dbpath"])
            .output()
            .ok()
            .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
            .filter(|database| database.starts_with('/') && Path::new(database).is_dir())
            .is_some_and(|database| {
                let link = root.join(database.trim_start_matches('/'));
                link.parent()
                    .is_some_and(|parent| std::fs::create_dir_all(parent).is_ok())
                    && std::os::unix::fs::symlink(&database, &link).is_ok()
            })
    };
    let downloaded = prepared
        && Command::new("zypper")
            .arg("--non-interactive")
            .arg("--installroot")
            .arg(&root)
            .arg("--pkg-cache-dir")
            .arg(&cache)
            .args(["install", "--download-only"])
            .args(names)
            .status()
            .is_ok_and(|status| status.success());
    let moved = downloaded && move_rpms(&cache, into);
    let _ = std::fs::remove_dir_all(&scratch);
    moved
}

/// Move every package under a folder, which zypper sorts by repository and
/// architecture, into one folder.
fn move_rpms(from: &Path, into: &Path) -> bool {
    let Ok(listing) = std::fs::read_dir(from) else {
        return false;
    };
    listing.flatten().all(|item| {
        let path = item.path();
        if path.is_dir() {
            move_rpms(&path, into)
        } else if path.extension().is_some_and(|extension| extension == "rpm") {
            std::fs::rename(&path, into.join(item.file_name())).is_ok()
                || std::fs::copy(&path, into.join(item.file_name())).is_ok()
        } else {
            true
        }
    })
}

fn dnf_download(names: &[String], complete: bool, into: &Path) -> bool {
    let mut command = Command::new("dnf");
    command.args(["download", "--resolve"]);
    if complete {
        command.arg("--alldeps");
    }
    command.arg("--destdir").arg(into).arg("--").args(names);
    command.status().is_ok_and(|status| status.success())
}

pub fn run(
    command: BundleCommand,
    catalog: &Catalog,
    platform: &LinuxInfo,
    as_json: bool,
) -> Result<()> {
    match command {
        BundleCommand::Create {
            directory,
            ids,
            complete,
            dry_run,
        } => {
            if as_json && !dry_run {
                bail!("--json shows bundles only with --dry-run");
            }
            for id in &ids {
                crate::find(catalog, id)?;
            }
            let scratch = bundle::scratch().context("cannot create a scratch folder")?;
            let found =
                bundle::contents(&ids, catalog, platform, complete, &doctor::Here, &scratch)?;
            let _ = std::fs::remove_dir_all(&scratch);
            if as_json {
                crate::json::print(
                    "bundle",
                    serde_json::json!({
                        "entries": found.entries,
                        "downloads": found.downloads.iter().map(|download| serde_json::json!({
                            "url": download.url,
                            "file": download.file,
                            "checksum": download.checksum,
                        })).collect::<Vec<_>>(),
                        "dnf": found.dnf,
                        "zypper": found.zypper,
                        "flatpaks": found.flatpaks,
                        "complete": complete,
                    }),
                );
                return Ok(());
            }
            for entry in &found.entries {
                match (&entry.network, &entry.flatpak) {
                    (None, Some(id)) => {
                        println!("Offline: {} (the Flatpak {id})", printable(&entry.name))
                    }
                    (None, None) => println!("Offline: {}", printable(&entry.name)),
                    (Some(why), _) => {
                        println!("Needs the network: {} ({why})", printable(&entry.name))
                    }
                }
            }
            let files = found
                .downloads
                .iter()
                .filter(|download| !download.file.ends_with(".sig"))
                .count();
            if !found.dnf.is_empty() {
                println!(
                    "dnf downloads {} with their dependencies.",
                    found.dnf.join(", ")
                );
            } else if !found.zypper.is_empty() {
                println!(
                    "zypper downloads {} with {}, as you, without root.",
                    found.zypper.join(", "),
                    if complete {
                        "every dependency"
                    } else {
                        "the dependencies this machine lacks"
                    }
                );
            } else if files > 0 || found.flatpaks.is_empty() {
                println!(
                    "{files} package {} to download{}.",
                    if files == 1 { "file" } else { "files" },
                    if complete {
                        ", every dependency"
                    } else {
                        ", with the dependencies this machine lacks"
                    }
                );
            }
            if !found.flatpaks.is_empty() {
                println!(
                    "flatpak create-usb copies {}, with the runtimes they need, from this machine's installation.",
                    found
                        .flatpaks
                        .iter()
                        .map(|flatpak| printable(&flatpak.reference))
                        .collect::<Vec<_>>()
                        .join(", ")
                );
            }
            if dry_run {
                for download in &found.downloads {
                    println!("  {}", printable(&download.url));
                }
                println!("Dry run: nothing was downloaded.");
                return Ok(());
            }
            if !found.entries.iter().any(|entry| entry.offline) {
                bail!("none of these entries can be bundled; they all need the network");
            }
            let tools = bundle::Tools {
                system: &doctor::Here,
                download: &curl,
                dnf_download: &dnf_download,
                zypper_download: &zypper_download,
                create_usb: &create_usb,
                flatpak_key: &flatpak_key,
            };
            let this =
                std::env::current_exe().context("cannot find the Helix Toolbox executable")?;
            let build = crate::inspect::build();
            let manifest = bundle::create(
                &directory,
                &found,
                platform,
                complete,
                Some((&this, crate::VERSION, build.release)),
                history::now(),
                &tools,
            )?;
            let bytes: u64 = manifest.files.iter().map(|file| file.bytes).sum::<u64>()
                + folder_bytes(&directory.join(bundle::FLATPAKS));
            println!(
                "Made {} ({} files, {:.1} MB) for {} {}.\nCopy the folder over; on the other machine, inside it: ./helix-toolbox bundle install .",
                directory.display(),
                manifest.files.len(),
                bytes as f64 / 1e6,
                manifest.distribution,
                manifest.architecture
            );
            Ok(())
        }
        BundleCommand::Verify { directory } => {
            let manifest = bundle::verify(&directory, platform)?;
            if as_json {
                crate::json::print(
                    "bundle",
                    serde_json::to_value(&manifest).unwrap_or_default(),
                );
                return Ok(());
            }
            println!(
                "{}: made for {} {} with Helix Toolbox {}{}; {} files, every one matching its checksum.",
                directory.display(),
                printable(&manifest.distribution),
                printable(&manifest.architecture),
                printable(&manifest.helixforge),
                if manifest.release {
                    " (a release build)"
                } else {
                    ""
                },
                manifest.files.len()
            );
            for flatpak in &manifest.flatpaks {
                println!(
                    "  Flatpak: {} at commit {}, from {}",
                    printable(&flatpak.reference),
                    &flatpak.commit[..12],
                    printable(&flatpak.remote)
                );
            }
            for entry in &manifest.entries {
                match &entry.network {
                    None => println!("  Offline: {}", printable(&entry.name)),
                    Some(why) => println!(
                        "  Needs the network: {} ({})",
                        printable(&entry.name),
                        printable(why)
                    ),
                }
            }
            Ok(())
        }
        BundleCommand::Install {
            directory,
            trust_bundle,
            dry_run,
            yes,
        } => {
            let manifest = bundle::verify(&directory, platform)?;
            println!(
                "The bundle matches its checksums: {} files for {}.",
                manifest.files.len(),
                printable(&manifest.distribution)
            );
            let planned = bundle::plan_install(
                &directory,
                &manifest,
                &[],
                platform,
                &doctor::Here,
                trust_bundle,
            )?;
            crate::confirm_and_run(catalog, platform, &planned, dry_run, yes, "INSTALL")
        }
    }
}