Skip to main content

isothrum_machine/install/linux/
scripts.rs

1//! The root scripts behind the installs on Linux: the vendors' apt and rpm repositories, and the
2//! distributions' own packages. Every repository's signing key is checked against its
3//! fingerprint, pinned here, before apt or dnf trusts it; no vendor install script runs as root.
4
5use crate::host::{HostOs, LinuxPackages};
6use crate::install::root::{NEED_CURL, NEED_GPG, NEED_UNZIP, RootScript, check_keys};
7use crate::install::steps::NOT_SERVED;
8use crate::providers::{Helper, Provider, helpers};
9
10/// The distro's codename as the vendors' repos name it (`$codename`): an Ubuntu derivative like
11/// Mint uses its Ubuntu base's. For the Debian family (Debian itself, Kali, Devuan: `ID_LIKE`
12/// without ubuntu), `$debian_base` names the suites to try when a vendor has none for this
13/// codename: the base's (`DEBIAN_CODENAME`, LMDE), then Debian's stable releases, whose packages
14/// a derivative runs (Kali's `kali-rolling` is served by no vendor; HashiCorp serves trixie and
15/// bookworm). Empty elsewhere: an Ubuntu release Debian's packages don't fit.
16const CODENAME: &str = r#"codename="$(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}")"; [ -n "$codename" ] || codename="$(lsb_release -cs)"; debian_base="$(. /etc/os-release && case " $ID ${ID_LIKE:-} " in *ubuntu*) ;; *debian*) echo "${DEBIAN_CODENAME:-} trixie bookworm" ;; esac)""#;
17
18/// A vendor's apt repository: where its packages and its signing key are, the key's pinned
19/// fingerprint, and the name its keyring and its source list take here.
20struct VendorRepo {
21    /// Who signs it, as a refusal names them.
22    vendor: &'static str,
23    /// Its signing key's fingerprint, pinned (40 hex digits).
24    fingerprint: &'static str,
25    /// Where its signing key is (a shell word: it may use `$repo`).
26    key_url: &'static str,
27    /// The repository (a shell word: it may use `$dist`).
28    repo: &'static str,
29    /// Its suite: `$codename` for one per distro release.
30    suite: &'static str,
31    component: &'static str,
32    /// The keyring's and the source list's name: `/etc/apt/keyrings/<name>.gpg`,
33    /// `/etc/apt/sources.list.d/<name>.list`.
34    name: &'static str,
35    /// Where to install from instead when the repository has no packages for this release; none
36    /// for a suite every release shares, or a release the caller has checked already.
37    by_hand: Option<&'static str>,
38}
39
40/// `release_served <repo> <suite>`: whether apt repository `<repo>` has packages for `<suite>`,
41/// by its `Release` file. A 2xx answer is yes and a 404 no; anything else (no answer at all: a
42/// DNS failure, a proxy, a timeout; or a server error) stops the script saying the repository
43/// couldn't be reached, so a network fault is never taken for a release the vendor doesn't serve.
44const RELEASE_SERVED: &str = r#"release_served() { served=$(curl -s -o /dev/null -w '%{http_code}' "$1/dists/$2/Release" || true); case "$served" in 2??) return 0 ;; 404) return 1 ;; *) echo "Couldn't reach $1 (HTTP ${served:-none}). Check this machine's internet access or proxy, then try again." >&2; exit 1 ;; esac; }"#;
45
46/// curl, then [`RELEASE_SERVED`]: what a script needs before it asks a vendor's repository
47/// anything.
48fn fetch_prelude() -> String {
49    format!("{NEED_CURL}; {RELEASE_SERVED}")
50}
51
52/// [`apt_repo_setup`] after [`fetch_prelude`]: a vendor's apt repository on a machine that may
53/// lack curl.
54fn apt_repo_script(r: &VendorRepo) -> String {
55    format!("{}; {}", fetch_prelude(), apt_repo_setup(r))
56}
57
58/// Sets up `r` for apt, the same way for every vendor: the suite checked when releases have their
59/// own ([`RELEASE_SERVED`]), the key downloaded, checked against its fingerprint and only then
60/// made a keyring under `/etc/apt/keyrings`, the source restricted to this machine's architecture
61/// and to that key, and apt's lists updated. `--batch --yes`: a second run (after a partial one)
62/// overwrites the keyring instead of asking on a terminal it doesn't have. Runs in
63/// a [`RootScript`], after [`fetch_prelude`].
64fn apt_repo_setup(r: &VendorRepo) -> String {
65    let VendorRepo {
66        vendor,
67        fingerprint,
68        key_url,
69        repo,
70        suite,
71        component,
72        name,
73        by_hand,
74    } = r;
75    // No packages for this release: the Debian family's fallbacks (`$debian_base`, [`CODENAME`])
76    // in order, the first the vendor serves taken as the suite; none served, the refusal.
77    let suite_check = by_hand.map(|url| {
78        format!(
79            r#"; release_served "$repo" "{suite}" || {{ for alt in ${{debian_base:-}}; do if release_served "$repo" "$alt"; then echo "{vendor} has no packages for {suite}: installing its $alt ones, which this Debian derivative runs."; codename="$alt"; break; fi; done; release_served "$repo" "{suite}" || {{ echo "{vendor} has no packages for {suite} yet. Install it from {url}" >&2; exit 1; }}; }}"#
80        )
81    });
82    format!(
83        r#"repo="{repo}"{suite_check}; {NEED_GPG}; curl -fsSL "{key_url}" -o "$d/key"; {check}; install -m 0755 -d /etc/apt/keyrings; gpg --batch --yes --dearmor --homedir "$d/gnupg" -o /etc/apt/keyrings/{name}.gpg "$d/key"; echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/{name}.gpg] $repo {suite} {component}" > /etc/apt/sources.list.d/{name}.list; apt-get update"#,
84        suite_check = suite_check.unwrap_or_default(),
85        check = check_keys(&[fingerprint], vendor),
86    )
87}
88
89/// HashiCorp's package signing key (`security+packaging@hashicorp.com`, created 2026-09-09,
90/// expires 2031-09-08), the one apt.releases.hashicorp.com serves at `/gpg` and signs its
91/// `InRelease` files with; keys.openpgp.org and keyserver.ubuntu.com have the same. When HashiCorp
92/// rotates it, installs stop with "isn't the expected one" until this is updated.
93const HASHICORP: VendorRepo = VendorRepo {
94    vendor: "HashiCorp",
95    fingerprint: "D55C0D1AC78A8D8126CB631CFC9CA96ACA026560",
96    key_url: "https://apt.releases.hashicorp.com/gpg",
97    repo: "https://apt.releases.hashicorp.com",
98    suite: "$codename",
99    component: "main",
100    name: "hashicorp",
101    by_hand: Some("https://developer.hashicorp.com/terraform/install"),
102};
103
104/// HashiCorp's apt repo, then terraform.
105#[must_use]
106pub fn terraform_script() -> RootScript {
107    RootScript::new(format!("{CODENAME}; {}; apt-get install -y terraform", apt_repo_script(&HASHICORP)))
108}
109
110/// HashiCorp's apt repo, then Vagrant: the distributions' own package is older than projects need
111/// (Debian 13 ships 2.3.8; Vagrantfiles commonly need 2.4.0 or later), so a setup that installed it
112/// left a machine that refused them.
113#[must_use]
114pub fn vagrant_script() -> RootScript {
115    const VAGRANT: VendorRepo = VendorRepo {
116        by_hand: Some("https://developer.hashicorp.com/vagrant/install"),
117        ..HASHICORP
118    };
119    RootScript::new(format!("{CODENAME}; {}; apt-get install -y vagrant", apt_repo_script(&VAGRANT)))
120}
121
122/// HashiCorp's apt repo, then the Vagrant VMware Utility, whose package generates its
123/// certificates and enables and starts its service, with `net-tools`: vagrant-vmware-desktop
124/// reads the routing table with its `netstat` before it makes a private network, and Debian 13
125/// and recent Ubuntu ship none ([`crate::providers::vmware_utility`]). `--reinstall`: an install
126/// that is there already has its package configured again, which restarts a service that had
127/// stopped.
128#[must_use]
129pub fn vmware_utility_script() -> RootScript {
130    // HashiCorp's repository, but a release it doesn't serve yet is sent to the utility's own page.
131    let repo = VendorRepo {
132        by_hand: Some("https://developer.hashicorp.com/vagrant/install/vmware"),
133        ..HASHICORP
134    };
135    RootScript::new(format!(
136        "{CODENAME}; {}; apt-get install -y --reinstall vagrant-vmware-utility net-tools",
137        apt_repo_script(&repo)
138    ))
139}
140
141/// Oracle's VirtualBox archive signing key (`info@virtualbox.org`, "Oracle Corporation (VirtualBox
142/// archive signing key)"), the one www.virtualbox.org serves as `oracle_vbox_2016.asc` and
143/// download.virtualbox.org signs its `InRelease` files with.
144const ORACLE: VendorRepo = VendorRepo {
145    vendor: "Oracle",
146    fingerprint: "B9F8D658297AF3EFC18D5CDFA2F683C52980AECF",
147    key_url: "https://www.virtualbox.org/download/oracle_vbox_2016.asc",
148    repo: "https://download.virtualbox.org/virtualbox/debian",
149    suite: "$codename",
150    component: "contrib",
151    name: "virtualbox",
152    by_hand: Some("https://www.virtualbox.org/wiki/Linux_Downloads"),
153};
154
155/// What builds a kernel driver here, as `$build` (packages for apt): the compiler, make, perl and
156/// kmod (`modprobe`), the running kernel's own headers (`linux-headers-$(uname -r)`), and its
157/// flavour's header package, which brings each later kernel's headers with it
158/// (`linux-headers-amd64` on Debian and Kali, `linux-headers-generic` on Ubuntu: the release's
159/// tail that has a header package). When the package sources no longer have the running kernel's
160/// headers (a machine not restarted since a kernel update: Debian's archive drops older kernels'),
161/// the flavour's kernel comes with its headers and `$reboot` is set: the driver is built when the
162/// computer starts that kernel (VirtualBox's `vboxdrv.sh start`, DKMS at the kernel's install).
163/// Requesting the flavour's headers alone, as VirtualBox's recommends did, brought that newer
164/// kernel's headers but not the running one's, so the driver never built. The other families
165/// name them otherwise, where the guided setup doesn't install yet (it installs through apt):
166/// Fedora `kernel-devel-$(uname -r)`, openSUSE `kernel-default-devel`, Arch `linux-headers`.
167const KERNEL_BUILD: &str = r#"kver="$(uname -r)"; flavour=""; f="$kver"; while [ "${f#*-}" != "$f" ]; do f="${f#*-}"; if apt-cache policy "linux-headers-$f" 2>/dev/null | grep -q 'Candidate: [0-9]'; then flavour="$f"; break; fi; done; build="gcc make perl kmod"; reboot=""; if apt-cache policy "linux-headers-$kver" 2>/dev/null | grep -q 'Candidate: [0-9]'; then build="$build linux-headers-$kver${flavour:+ linux-headers-$flavour}"; elif [ -n "$flavour" ]; then build="$build linux-image-$flavour linux-headers-$flavour"; reboot=1; else echo "VirtualBox builds its kernel driver with the running kernel's headers (linux-headers-$kver), which this machine's package sources don't have. Update the kernel, restart the computer, then install VirtualBox again." >&2; exit 1; fi"#;
168
169/// The distro's own `virtualbox` when it has one (Ubuntu), else Oracle's apt repo and its newest
170/// `virtualbox-X.Y` (Debian ships none in main, so `apt-get install virtualbox` failed); with what
171/// builds its kernel driver (`KERNEL_BUILD`), and without its recommends: a PDF viewer, Qt's
172/// translations and the newest kernel's headers (and so that kernel) came with them, which a
173/// headless VirtualBox that Vagrant drives never uses. When the running kernel's headers were gone,
174/// it says the driver waits for a restart.
175#[must_use]
176pub fn virtualbox_script() -> RootScript {
177    RootScript::new(format!(
178        r#"apt-get update; {KERNEL_BUILD}; if apt-cache policy virtualbox 2>/dev/null | grep -q 'Candidate: [0-9]'; then apt-get install -y --no-install-recommends virtualbox $build; else {CODENAME}; {}; pkg="$(apt-cache search --names-only '^virtualbox-[0-9]+\.[0-9]+$' | awk '{{print $1}}' | sort -V | tail -n 1)"; [ -n "$pkg" ] || {{ echo "No VirtualBox package found in Oracle's repo. Install it from https://www.virtualbox.org/wiki/Linux_Downloads" >&2; exit 1; }}; apt-get install -y --no-install-recommends "$pkg" $build; fi; [ -z "$reboot" ] || echo "VirtualBox is installed. This computer runs a kernel ($kver) whose headers its package sources no longer have, so the newer kernel came with its headers: restart the computer to start it, and VirtualBox's driver is built then.""#,
179        apt_repo_script(&ORACLE)
180    ))
181}
182
183/// Docker's release key (`docker@docker.com`, Docker Release (CE deb)), the one download.docker.com
184/// serves at `/linux/{ubuntu,debian,raspbian}/gpg` and signs its `InRelease` files with (from its
185/// signing subkey D3306A018370199E527AE7997EA0A9C3F273FCD8); keyserver.ubuntu.com has the same.
186/// Its repository is one per distro (`$dist`, see [`DOCKER_DIST`]), whose release is checked there
187/// (a release it doesn't serve gets the distribution's own Docker), so not again here.
188const DOCKER: VendorRepo = VendorRepo {
189    vendor: "Docker",
190    fingerprint: "9DC858229FC7DD38854AE2D88D81803C0EBFCD88",
191    key_url: "$repo/gpg",
192    repo: "https://download.docker.com/linux/$dist",
193    suite: "$codename",
194    component: "stable",
195    name: "docker",
196    by_hand: None,
197};
198
199/// Docker Engine, then the user into the `docker` group so the CLI can reach the daemon without
200/// root (pkexec runs as root, so `$USER` there is root: the name comes from the app). The group
201/// applies from the next login.
202///
203/// On Ubuntu, Debian and Raspbian, and their derivatives (on the Ubuntu or Debian release they are
204/// built on, when they say it), it sets up Docker's apt repository, the way Docker documents it,
205/// with Docker's key checked against its pinned fingerprint. Where that repository has no packages
206/// for the release (Kali's rolling one, Devuan's, a Debian or Ubuntu newer than Docker serves yet:
207/// its `Release` file answers 404), it installs the distribution's own Docker (`docker.io` and its Compose), signed by the
208/// distribution's own keys. When download.docker.com can't be reached, it stops and says so. Elsewhere
209/// it stops, changing nothing, with a code read as [`StepFailed::NotServed`](crate::install::StepFailed::NotServed) (a UI says where to get Docker): Docker's convenience
210/// script (get.docker.com) can't be held to a key (it fetches the key and installs what it signed
211/// in one go), so it never runs as root from here.
212#[must_use]
213pub fn docker_script(user: Option<&str>) -> RootScript {
214    let mut s = format!(
215        "{}; {DOCKER_DIST}; [ -n \"$dist\" ] || exit {NOT_SERVED}; if [ -n \"$own\" ]; then {DISTRIBUTION_DOCKER}; else {}; apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin; fi",
216        fetch_prelude(),
217        apt_repo_setup(&DOCKER)
218    );
219    if let Some(u) = user.filter(|u| valid_user(u)) {
220        s = format!("{s}; usermod -aG docker {u}; echo 'Added {u} to the docker group: log out and back in (or restart) for it to apply.'");
221    }
222    RootScript::new(s)
223}
224
225/// Which of Docker's apt repositories fits this system (`$dist`, empty when none does) and its
226/// codename there; `$own` set when that repository has no packages for it ([`RELEASE_SERVED`]: a
227/// 404, never an unreachable server, which stops the script), so the distribution's own Docker is
228/// installed. A derivative is known by `ID_LIKE`, on its base's release: Ubuntu's
229/// (`UBUNTU_CODENAME`, Mint), Debian's (`DEBIAN_CODENAME`, LMDE), else its own (Kali, Devuan),
230/// which Docker doesn't serve. Raspbian Trixie has none of Docker's: Debian's serves it (as
231/// get.docker.com does).
232const DOCKER_DIST: &str = r#". /etc/os-release; dist=""; own=""; codename="${VERSION_CODENAME:-}"; case "$ID" in ubuntu|debian|raspbian) dist="$ID";; *) case " ${ID_LIKE:-} " in *" ubuntu "*) dist=ubuntu;; *" debian "*) dist=debian; codename="${DEBIAN_CODENAME:-$codename}";; esac;; esac; [ "$dist" != ubuntu ] || codename="${UBUNTU_CODENAME:-$codename}"; [ "$dist$codename" != raspbiantrixie ] || dist=debian; command -v apt-get >/dev/null || dist=""; if [ -n "$dist" ] && ! release_served "https://download.docker.com/linux/$dist" "$codename"; then own=1; fi"#;
233
234/// The distribution's own Docker: `docker.io`, and its Compose plugin (`docker-compose-v2` on
235/// Ubuntu, `docker-compose` on Debian and Kali), from the distribution's archive.
236const DISTRIBUTION_DOCKER: &str = r#"echo "Docker's apt repository has no packages for $dist $codename: installing the distribution's own Docker (docker.io)."; apt-get update; apt-get install -y docker.io; if apt-cache show docker-compose-v2 >/dev/null 2>&1; then apt-get install -y docker-compose-v2; else apt-get install -y docker-compose; fi"#;
237
238/// The AWS CLI team's signing key (`aws-cli@amazon.com`, created 2019-09-18, expires 2027-07-01 as
239/// published), as AWS publishes it in "Installing or updating to the latest version of the AWS
240/// CLI" (Linux, "Verify the integrity and authenticity of the downloaded zip file"). An expired
241/// copy still verifies older signatures; refresh it from that page when AWS extends it.
242const AWS_CLI_KEY: &str = include_str!("keys/aws-cli.asc");
243/// Its fingerprint, as that page gives it (FB5D B77F D5C1 18B8 0511 ADA8 A631 0ACC 4672 475C).
244pub const AWS_CLI_KEY_FINGERPRINT: &str = "FB5DB77FD5C118B80511ADA8A6310ACC4672475C";
245
246/// AWS CLI v2 from Amazon's official bundle, unpacked and installed from a private directory.
247/// The distro `awscli` package is v1, which has no `aws login` (the app needs v2 >= 2.32).
248/// `uname -m` is `x86_64` or `aarch64`, matching the URLs. The bundle must carry a valid signature
249/// (its `.sig`) by AWS's key, embedded here (`AWS_CLI_KEY`): gpgv, with only that key, must
250/// report it by its fingerprint. Then `unzip -t` checks the archive is whole before anything
251/// in it runs.
252#[must_use]
253pub fn awscli_script() -> RootScript {
254    RootScript::new(format!(
255        r#"{NEED_CURL}; url="https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m).zip"; curl -fsSL "$url" -o "$d/awscliv2.zip"; curl -fsSL "$url.sig" -o "$d/awscliv2.zip.sig"; {}; {NEED_UNZIP}; unzip -tq "$d/awscliv2.zip" >/dev/null; unzip -oq "$d/awscliv2.zip" -d "$d"; "$d/aws/install" --update"#,
256        aws_verify()
257    ))
258}
259
260/// Stops the script unless `"$d/awscliv2.zip.sig"` is a valid signature of `"$d/awscliv2.zip"`
261/// by [`AWS_CLI_KEY`].
262fn aws_verify() -> String {
263    let key = AWS_CLI_KEY.trim_end();
264    format!(
265        r#"{NEED_GPG}; cat > "$d/aws-cli.asc" <<'AWS_CLI_KEY'
266{key}
267AWS_CLI_KEY
268gpg --batch --yes --dearmor --homedir "$d/gnupg" -o "$d/aws-cli.gpg" "$d/aws-cli.asc"; gpgv --homedir "$d/gnupg" --status-fd 1 --keyring "$d/aws-cli.gpg" "$d/awscliv2.zip.sig" "$d/awscliv2.zip" 2>/dev/null | grep -q '^\[GNUPG:\] VALIDSIG {AWS_CLI_KEY_FINGERPRINT} ' || {{ echo "The AWS CLI download isn't signed by AWS's key ({AWS_CLI_KEY_FINGERPRINT}). Nothing was installed." >&2; exit 1; }}"#
269    )
270}
271
272/// Microsoft's package signing key (`gpgsecurity@microsoft.com`, "Microsoft (Release signing)"),
273/// the one packages.microsoft.com serves at `/keys/microsoft.asc` and signs the azure-cli
274/// repository's `InRelease` files with (its key id EB3E94ADBE1229CF).
275const MICROSOFT: VendorRepo = VendorRepo {
276    vendor: "Microsoft",
277    fingerprint: "BC528686B50D79E339D3721CEB3E94ADBE1229CF",
278    key_url: "https://packages.microsoft.com/keys/microsoft.asc",
279    repo: "https://packages.microsoft.com/repos/azure-cli",
280    suite: "$codename",
281    component: "main",
282    name: "azure-cli",
283    by_hand: Some("https://learn.microsoft.com/cli/azure/install-azure-cli-linux"),
284};
285
286/// Microsoft's azure-cli apt repository for this distro's codename, then `azure-cli`: what
287/// Microsoft's install script (aka.ms/InstallAzureCLIDeb) sets up, without running that script as
288/// root.
289#[must_use]
290pub fn azurecli_script() -> RootScript {
291    RootScript::new(format!("{CODENAME}; {}; apt-get install -y azure-cli", apt_repo_script(&MICROSOFT)))
292}
293
294/// Google Cloud's package signing key ("Artifact Registry Repository Signer"), the one
295/// packages.cloud.google.com serves at `/apt/doc/apt-key.gpg` and signs the cloud-sdk
296/// repository's `InRelease` files with. One suite for every release.
297const GOOGLE: VendorRepo = VendorRepo {
298    vendor: "Google Cloud",
299    fingerprint: "35BAA0B33E9EB396F59CA838C0BA5CE6DC6315A3",
300    key_url: "https://packages.cloud.google.com/apt/doc/apt-key.gpg",
301    repo: "https://packages.cloud.google.com/apt",
302    suite: "cloud-sdk",
303    component: "main",
304    name: "google-cloud-sdk",
305    by_hand: None,
306};
307
308/// Google Cloud's apt repository, then `google-cloud-cli` (gcloud), system-wide: what Google
309/// documents for Debian and Ubuntu, in place of its install script.
310#[must_use]
311pub fn gcloud_script() -> RootScript {
312    RootScript::new(format!("{}; apt-get install -y google-cloud-cli", apt_repo_script(&GOOGLE)))
313}
314
315/// libvirt, with what `vagrant plugin install vagrant-libvirt` compiles against: libvirt's headers
316/// (`libvirt-dev`), a C compiler and make (`build-essential`), `pkg-config`, and Ruby's headers
317/// for a distribution's Vagrant (which builds on the system Ruby). Without them the plugin's
318/// install fails building its native extension. With the programs its VMs need beside it
319/// (`apt_install_with_helpers`). Then the user joins the `libvirt` group (and `kvm`, where the
320/// distribution has one), so Vagrant reaches `qemu:///system` and `/dev/kvm` without root; the
321/// groups apply from the next login.
322#[must_use]
323pub fn libvirt_script(user: Option<&str>) -> RootScript {
324    then_libvirt_groups(
325        &apt_install_with_helpers(
326            Provider::Libvirt,
327            "libvirt-daemon-system libvirt-dev build-essential pkg-config ruby-dev virt-manager",
328        ),
329        user,
330    )
331}
332
333/// QEMU and its disk tools, with the programs its VMs need beside it
334/// (`apt_install_with_helpers`: `mkisofs`, virtiofsd), then the user into the group `/dev/kvm`
335/// belongs to, so vagrant-qemu boots VMs with KVM (`accel=kvm`, as Vagrantfiles ask on Linux)
336/// without root; the group applies from the next login.
337#[must_use]
338pub fn qemu_script(user: Option<&str>) -> RootScript {
339    then_kvm_group(&apt_install_with_helpers(Provider::Qemu, "qemu-system qemu-utils"), user)
340}
341
342/// apt's install of `packages`, with the packages of the programs `provider`'s VMs need beside it
343/// on Linux ([`helpers`], the list its detection reads it installed by): `genisoimage` (which has
344/// `mkisofs`) in every Debian and Ubuntu release, so with the rest; `virtiofsd` its own package
345/// from Debian 12 and Ubuntu 23.10 on, QEMU's own (`/usr/lib/qemu/virtiofsd`) before, so
346/// installed where the release has it. Separate statements: a failure inside an `&&` chain doesn't
347/// stop a script that runs `set -e`.
348fn apt_install_with_helpers(provider: Provider, packages: &str) -> String {
349    let mut install = format!("apt-get update; apt-get install -y {packages}");
350    let mut where_released = Vec::new();
351    for &helper in helpers(provider, HostOs::Linux) {
352        let package = helper.package(LinuxPackages::Apt);
353        if helper == Helper::Virtiofsd {
354            where_released.push(format!("if apt-cache show {package} >/dev/null 2>&1; then apt-get install -y {package}; fi"));
355        } else {
356            install.push(' ');
357            install.push_str(package);
358        }
359    }
360    std::iter::once(install).chain(where_released).collect::<Vec<_>>().join("; ")
361}
362
363/// dnf's install of `packages`, with the packages of the programs `provider`'s VMs need beside it
364/// on Linux ([`helpers`]): every Fedora release from 36 on has them.
365fn dnf_install_with_helpers(provider: Provider, packages: &str) -> String {
366    let mut line = format!("dnf install -y {packages}");
367    for helper in helpers(provider, HostOs::Linux) {
368        line.push(' ');
369        line.push_str(helper.package(LinuxPackages::Dnf));
370    }
371    line
372}
373
374/// The KVM device.
375const KVM_DEVICE: &str = "/dev/kvm";
376
377/// `install`, then the user `user` (a valid login name only) into the group the KVM device
378/// belongs to: it applies from the next login.
379fn then_kvm_group(install: &str, user: Option<&str>) -> RootScript {
380    match user.filter(|u| valid_user(u)) {
381        Some(u) => RootScript::new(format!("{install}; {}", join_kvm_group(u, KVM_DEVICE))),
382        None => RootScript::new(install),
383    }
384}
385
386/// `install`, then the user `user` (a valid login name only) into the `libvirt` group and the
387/// KVM device's: they apply from the next login.
388fn then_libvirt_groups(install: &str, user: Option<&str>) -> RootScript {
389    match user.filter(|u| valid_user(u)) {
390        Some(u) => RootScript::new(format!(
391            "{install}; usermod -aG libvirt {u}; {}; echo 'Added {u} to the libvirt group: log out and back in (or restart) for it to apply.'",
392            join_kvm_group(u, KVM_DEVICE)
393        )),
394        None => RootScript::new(install),
395    }
396}
397
398/// User `u` into the group `dev` (the KVM device) belongs to, saying so: `kvm` where a
399/// distribution makes it `0660` (Debian, Ubuntu, Kali, openSUSE); joining it does no harm where
400/// it is `0666` (Fedora, Arch). Without the device (virtualization off in the firmware), or when it
401/// is root's, the `kvm` group, where the distribution has one.
402fn join_kvm_group(u: &str, dev: &str) -> String {
403    format!(
404        "g=$(stat -c %G {dev} 2>/dev/null || true); case \"$g\" in ''|root|UNKNOWN) g=kvm;; esac; if getent group \"$g\" >/dev/null; then usermod -aG \"$g\" {u} && echo \"Added {u} to the $g group, which opens {dev}: log out and back in (or restart) for it to apply.\"; fi"
405    )
406}
407
408/// A login name safe to put in a shell script unquoted.
409pub(crate) fn valid_user(u: &str) -> bool {
410    !u.is_empty()
411        && u.len() <= 32
412        && u.chars().next().is_some_and(|c| c.is_ascii_lowercase() || c == '_')
413        && u.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
414}
415
416// --- dnf: Fedora and the distributions built on it --------------------------------------------
417
418mod dnf;
419
420pub use dnf::{docker_dnf_script, libvirt_dnf_script, qemu_dnf_script, terraform_dnf_script, vagrant_dnf_script, virtualbox_dnf_script};
421
422#[cfg(test)]
423mod tests;