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
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, nix::NixArgs};

#[derive(Default, Clone)]
pub struct Nix {
    pub args: NixArgs
}

impl Nix {
    pub fn new(args: NixArgs) -> Self {
        Self { args }
    }

    pub fn impure(&mut self) -> &mut Self {
        self.args.impure = true;
        self
    }

    pub fn build_args(&self) -> String {
        let mut args = vec![];
        if self.args.impure {
            args.push("--impure".to_string());
        }
        args.join(" ")
    }
}

impl Extension for Nix {
    fn exec(
        &mut 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());
        }

        let args = self.build_args();

        Command::new("bash")
            .arg("-c")
            .arg(&format!("[ -f flake.nix ] || nix flake init {}", args))
            .current_dir(work_dir)
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .spawn()?
            .wait()?;

        let cmd = format!("nix develop {} -c {}", args, 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(())
    }

    fn format_command(&self, cmd: &str) -> String {
        let args = self.build_args();
        format!(
            "[ -f flake.nix ] || nix flake init {} ; nix develop {} -c {}",
            args, args, cmd
        )
    }
}