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
// Copyright (C) 2023 Andreas Hartmann <hartan@7x.de>
// GNU General Public License v3.0+ (https://www.gnu.org/licenses/gpl-3.0.txt)
// SPDX-License-Identifier: GPL-3.0-or-later

//! # Distrobox Environment Handler.
//!
//! [Distrobox][distrobox] is a collection of shell-scripts that serves the same purpose as
//! [toolbx][toolbx]: To provide pet-containers for e.g. development purposes
//!
//! [distrobox]: https://github.com/89luca89/distrobox
//! [toolbx]: https://containertoolbx.org/
use super::prelude::*;

use log;
use std::{io::IsTerminal, path::Path};

const DISTROBOX_ENV: &str = "/run/.containersetupdone";
const CONTAINER_ENV: &str = "/run/.containerenv";

#[derive(PartialEq, Eq, Debug, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Distrobox {
    name: String,
}

impl fmt::Display for Distrobox {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "distrobox '{}'", self.name)
    }
}

impl Distrobox {
    /// Start a Distrobox container with a given name.
    ///
    /// Checks if the distrobox container exists and starts it, if necessary. If `None` is given as
    /// name, will fall back to the default distrobox name and start that instead. Returns an error
    /// if unsuccessful.
    pub fn new(name: Option<String>) -> Result<Self, NewDistroboxError> {
        let name = match name {
            Some(name) if !name.is_empty() => name,
            _ => "my-distrobox".to_string(),
        };

        // Do an optimistic start:
        // - If the container exists and isn't started, it will be started
        // - If the container exists and is started, nothing happens
        // - If the container doesn't exist, we get an error and report that
        let output = std::process::Command::new("podman")
            .args(["start", &name])
            .output()
            .map_err(|e| match e.kind() {
                std::io::ErrorKind::NotFound => NewDistroboxError::NeedPodman,
                _ => NewDistroboxError::IoError(e),
            })?;
        if output.status.success() {
            // All good
            Ok(Self { name })
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.starts_with("Error: no container with name or ID")
                && stderr.contains("found: no such container")
            {
                Err(NewDistroboxError::NonExistent(name))
            } else {
                Err(NewDistroboxError::Podman(output))
            }
        }
    }

    /// Get the Toolbx container currently executing CNF.
    ///
    /// Will return an error if the current execution environment isn't Toolbx.
    pub fn current() -> Result<Self, CurrentDistroboxError> {
        if !detect() {
            return Err(CurrentDistroboxError::NotAToolbx);
        }

        let content = std::fs::read_to_string(CONTAINER_ENV).map_err(|e| {
            CurrentDistroboxError::Environment {
                env_file: CONTAINER_ENV.to_string(),
                source: e,
            }
        })?;
        let name = content
            .lines()
            .find(|line| line.contains("name=\""))
            .ok_or_else(|| CurrentDistroboxError::Name(CONTAINER_ENV.to_string()))?
            .trim_start_matches("name=\"")
            .trim_end_matches('"');

        Ok(Self {
            name: name.to_string(),
        })
    }
}

impl environment::IsEnvironment for Distrobox {
    type Err = Error;

    fn exists(&self) -> bool {
        if detect() {
            true
        } else if let Environment::Host(host) = environment::current() {
            host.execute(crate::environment::cmd!("distrobox", "--version"))
                .map(|mut cmd| {
                    async_std::task::block_on(async move {
                        cmd.stdout(async_process::Stdio::null())
                            .stderr(async_process::Stdio::null())
                            .status()
                            .await
                            .map(|status| status.success())
                            .unwrap_or(false)
                    })
                })
                .unwrap_or(false)
        } else {
            false
        }
    }

    fn execute(&self, command: CommandLine) -> Result<Command, Self::Err> {
        log::debug!(
            "Executing command '{}' in distrobox '{}'",
            command,
            self.name
        );

        let mut cmd: Command;
        match environment::current() {
            Environment::Distrobox(t) => {
                if self == &t {
                    // This is the toolbx container we are currently running in
                    // We expect toolbx containers to *always* run a unix OS, or at least something
                    // that has `sudo`.
                    if command.get_privileged() {
                        cmd = Command::new("sudo");
                        if !command.get_interactive() {
                            cmd.arg("-n");
                        }

                        cmd.arg(command.command());
                    } else {
                        cmd = Command::new(command.command());
                    }

                    cmd.args(command.args());
                } else {
                    return Err(Error::Unimplemented(
                        "running in a distrobox from another distrobox".to_string(),
                    ));
                }
            }
            Environment::Toolbx(_) => {
                return Err(Error::Unimplemented(
                    "running in a distrobox from a toolbx".to_string(),
                ));
            }
            Environment::Host(_) => {
                cmd = Command::new("distrobox");
                cmd.args(["enter", "--name", &self.name]);

                // Only attach to the tty if we really have a tty, too
                // FIXME: Is this really the correct way to check?
                if std::io::stdout().is_terminal() && std::io::stdin().is_terminal() {
                    cmd.arg("-T");
                }
                cmd.arg("--");

                // This is the real command we're looking for (with arguments)
                if command.get_privileged() {
                    cmd.args(["sudo", "-S", "-E"]);
                }

                cmd.arg(command.command()).args(command.args());

                log::debug!("Calling: {:?}", cmd);
            }
            #[cfg(test)]
            Environment::Mock(_) => unimplemented!(),
        }
        Ok(cmd)
    }
}

/// Detect if the current execution environment is a Toolbx container.
///
/// Checks for the presence of the `.toolboxenv` files.
pub fn detect() -> bool {
    Path::new(DISTROBOX_ENV).exists()
}

#[derive(Debug, ThisError)]
pub enum NewDistroboxError {
    #[error("working with toolbx containers requires the 'podman' executable")]
    NeedPodman,

    #[error("podman exited with non-zero code: {0:#?}")]
    Podman(std::process::Output),

    #[error("no toolbx with name {0} exists")]
    NonExistent(String),

    #[error("unknown I/O error occured")]
    IoError(#[from] std::io::Error),

    #[error("failed to determine default toolbx name")]
    UnknownDefault(#[from] DefaultToolbxError),
}

#[derive(Debug, ThisError)]
pub enum CurrentDistroboxError {
    #[error("cannot read toolbx info from environment file '{env_file}'")]
    Environment {
        env_file: String,
        source: std::io::Error,
    },

    #[error("program currently isn't run from a toolbx")]
    NotAToolbx,

    #[error("failed to read toolbx name from environment file '{0}'")]
    Name(String),
}

#[derive(Debug, ThisError)]
pub enum DefaultToolbxError {
    #[error("failed to read OS information from '{file}'")]
    UnknownOs {
        file: String,
        source: std::io::Error,
    },

    #[error("cannot determine OS ID from os-release info")]
    Id,

    #[error("cannot determine OS VERSION_ID from os-release info")]
    VersionId,
}

#[derive(Debug, ThisError)]
pub enum Error {
    #[error("cannot determine current working directory")]
    UnknownCwd(#[from] std::io::Error),

    #[error("not implemented: {0}")]
    Unimplemented(String),
}