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
use std::{
    env,
    process::{Command, ExitStatus, Stdio},
    sync::mpsc::Sender,
};
use users::get_current_username;

use crate::{exec, Extension};
use anyhow::Error;
use fluentci_types::Output;

#[derive(Default)]
pub struct Nix {}

impl Extension for Nix {
    fn exec(
        &self,
        cmd: &str,
        tx: Sender<String>,
        out: Output,
        last_cmd: bool,
        work_dir: &str,
    ) -> Result<ExitStatus, Error> {
        self.setup()?;

        if cmd.is_empty() {
            return Ok(ExitStatus::default());
        }

        Command::new("bash")
            .arg("-c")
            .arg("nix flake init")
            .current_dir(work_dir)
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .spawn()?
            .wait()?;

        let cmd = format!("nix develop -c {}", cmd);
        exec(&cmd, tx, out, last_cmd, work_dir)
    }

    fn setup(&self) -> Result<(), Error> {
        let user = match get_current_username() {
            Some(user) => user.to_string_lossy().to_string(),
            None => "root".to_string(),
        };

        env::set_var("USER", user);
        env::set_var("SHELL", "/bin/bash");
        
        let home = match env::var("HOME") {
            Ok(home) => home,
            Err(_) => "/root".to_string(),
        };
        let nix_path = format!("{}/.nix-profile/bin", home);
        env::set_var(
            "PATH",
            format!(
                "{}:{}:{}",
                env::var("PATH")?,
                "/nix/var/nix/profiles/default/bin",
                nix_path
            ),
        );

        let mut child = Command::new("sh")
            .arg("-c")
            .arg("type systemctl > /dev/null")
            .spawn()?;
        let status = child.wait()?;
        let init = match status.code() {
            Some(0) => "",
            _ => "--init none",
        };

        let linux = match std::env::consts::OS {
            "linux" => format!("linux --extra-conf 'sandbox = false' {}", init),
            _ => "".to_string(),
        };
        let mut child = Command::new("bash")
            .arg("-c")
            .arg(format!("type nix > /dev/null || curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | sh -s -- install {}", linux))
            
            .spawn()?;
        child.wait()?;

        let mut child = Command::new("bash")
            .arg("-c")
            .arg(format!("type nix > /dev/null || curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | sh -s -- install {} --no-confirm", linux))
            
            .spawn()?;
        child.wait()?;
        Ok(())
    }
}