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
//
// Wildland Project
//
// Copyright © 2022 Golem Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use std::path::PathBuf;
use std::sync::Arc;

use anyhow::Context as _;
use reedline_repl_rs::clap::{ArgMatches, Command};
use reedline_repl_rs::Repl;
use s_macro::s;
use thiserror::Error;
use wildland_cargo_lib::api::cargo_user::CargoUser;
use wildland_cargo_lib::api::CargoConfig;
use wildland_corex::dfs::interface::DfsFrontend;

use crate::dropins::lss::sledlss::SledLss;
use crate::dropins::sfo::sfo_for_local_fs::SfoForLocalFS;
use crate::plugins::cargo::cargo_lib::CargoLib;

#[tracing::instrument(level = "trace")]
fn default_path() -> std::path::PathBuf {
    std::path::PathBuf::from("/")
}

#[derive(derivative::Derivative)]
#[derivative(Default)] // todo derivative instead
pub struct Context {
    #[derivative(Default(value = "None"))]
    pub lss: Option<SledLss>,
    #[derivative(Default(value = "None"))]
    pub sfo: Option<SfoForLocalFS>,
    #[derivative(Default(value = "None"))]
    pub cargo_cfg: Option<CargoConfig>,
    #[derivative(Default(value = "None"))]
    pub cargo: Option<CargoLib>,
    #[derivative(Default(value = "None"))]
    pub cargo_user: Option<CargoUser>,
    #[derivative(Default(value = "default_path()"))]
    pub current_path: PathBuf,
}

#[derive(Error, Debug, Clone)]
pub enum ContextError {
    #[error("Cargo error: {0}")]
    Cargo(String),
    #[error("LSS error: {0}")]
    Lss(String),
    #[error("SFO error: {0}")]
    Sfo(String),
    #[error("Config error: {0}")]
    Config(String),
    #[error("CargoUser error: {0}")]
    CargoUser(String),
    #[error("Recoverable - {0}")]
    Recoverable(Box<ContextError>),
}

type ContextResult<T> = Result<T, ContextError>;

impl Context {
    #[tracing::instrument(level = "trace", skip_all)]
    pub fn show_state(&self) {
        match self.sfo {
            Some(_) => println!("[o] SFO: loaded"),
            None => println!("[x] SFO: not loaded"),
        }
        match self.lss {
            Some(_) => println!("[o] LSS: loaded"),
            None => println!("[x] LSS: not loaded"),
        }
        match self.cargo_cfg {
            Some(_) => println!("[o] CFG: loaded"),
            None => println!("[x] CFG: not loaded"),
        }
        match self.cargo {
            Some(_) => println!("[o] CARGO: loaded"),
            None => println!("[x] CARGO: not loaded"),
        }
        match self.cargo_user {
            Some(_) => println!("[o] USER: loaded"),
            None => println!("[x] USER: not loaded"),
        }
    }

    pub fn get_dfs(&self) -> ContextResult<Arc<dyn DfsFrontend>> {
        if self.cargo.is_none() {
            Err(ContextError::Cargo(s!(
                "DFS can not be enabled, no Cargo found"
            )))
        } else {
            Ok(self.cargo.as_ref().unwrap().dfs_api().clone())
        }
    }

    #[tracing::instrument(level = "trace", err(Debug), skip(self, lss))]
    pub fn set_lss(&mut self, lss: SledLss) -> ContextResult<()> {
        if self.cargo.is_some() {
            return Err(ContextError::Cargo(s!(
                "Cant set Cargo, its potentially used by Cargo Lib"
            )));
        }
        self.lss = Some(lss);
        Ok(())
    }

    #[tracing::instrument(level = "trace", err(Debug), skip(self))]
    pub fn set_lss_from_path(&mut self, path: &String) -> ContextResult<()> {
        if self.cargo.is_some() {
            return Err(ContextError::Lss(s!(
                "Cant set Cargo, its potentially used by Cargo Lib"
            )));
        }

        let lss_instance = SledLss::new(s!(path));
        self.lss = Some(lss_instance);
        Ok(())
    }

    #[tracing::instrument(level = "trace", err(Debug), skip(self))]
    pub fn init_sfo(&mut self, sfo_path: &str) -> ContextResult<()> {
        if self.cargo.is_some() {
            return Err(ContextError::Sfo(s!(
                "Cant set Cargo, its potentially used by Cargo Lib"
            )));
        }

        let sfo_instance = SfoForLocalFS::new(sfo_path);
        self.sfo = Some(sfo_instance);
        Ok(())
    }

    #[tracing::instrument(level = "trace", err(Debug), skip(self))]
    pub fn set_cargo_config(&mut self, cargo_cfg: CargoConfig) -> ContextResult<()> {
        if self.cargo.is_some() {
            return Err(ContextError::Config(s!(
                "Can't set Cargo, it's potentially used by Cargo Lib"
            )));
        }
        if self.cargo_cfg.is_some() {
            println!("replacing existing cargo config");
        }
        self.cargo_cfg = Some(cargo_cfg);
        Ok(())
    }

    #[tracing::instrument(level = "trace", err(Debug), skip(self))]
    pub fn set_cargo_config_from_path(&mut self, cargo_cfg: &str) -> ContextResult<()> {
        let cargocfg = crate::dropins::cargo_cfg::handler::load_json_config_from_file(cargo_cfg)
            .map_err(|e| ContextError::Config(e.to_string()))?;
        self.set_cargo_config(cargocfg)
    }

    #[tracing::instrument(level = "trace", err(Debug), skip(self, cargo))]
    pub fn set_cargo(&mut self, cargo: CargoLib) -> ContextResult<()> {
        if self.cargo.is_some() {
            return Err(ContextError::Cargo(s!(
                "Cargo is present, can't replace it implicitly, wipe it first"
            )));
        }

        self.cargo = Some(cargo);
        Ok(())
    }

    #[tracing::instrument(level = "trace", err(Debug), skip(self))]
    pub fn set_cargo_user(&mut self) -> ContextResult<()> {
        tracing::debug!("Setting/restoring cargo user");
        let cargo = self
            .cargo
            .as_ref()
            .context("Cargo is not present")
            .map_err(|e| ContextError::Cargo(e.to_string()))?;
        let cargo_user_opt = cargo.user_api().get_user();
        if let Ok(cargo_user) = cargo_user_opt {
            tracing::debug!("found cargo user");
            self.cargo_user = Some(cargo_user);
        } else {
            tracing::warn!("Cargo user not found, try creating one first");
            return Err(ContextError::Recoverable(Box::new(
                ContextError::CargoUser(s!("Cargo user not found, try creating one first")),
            )));
        }
        Ok(())
    }

    #[allow(dead_code)]
    pub fn set_all_refs(&mut self) -> ContextResult<()> {
        self.set_cargo_user()?;
        self.show_state();
        Ok(())
    }
    pub fn set_full_cargo(&mut self, cargo: CargoLib) -> ContextResult<()> {
        self.set_cargo(cargo)?;
        self.set_cargo_user()?;
        self.show_state();
        Ok(())
    }
}

#[tracing::instrument(level = "trace", err(Debug), skip(_args, context))]
fn aux_show_context(_args: ArgMatches, context: &mut Context) -> anyhow::Result<Option<String>> {
    context.show_state();
    Ok(Some(s!("")))
}

pub fn extend(repl: Repl<Context, anyhow::Error>) -> Repl<Context, anyhow::Error> {
    repl.with_command(
        Command::new("aux-ctx-show").about("show context"),
        aux_show_context,
    )
}

#[macro_export]
macro_rules! field_to_string {
    (cargo_cfg) => {
        "Cargo Config"
    };
    (sfo) => {
        "Special File Operations Service"
    };
    (lss) => {
        "Local Secure Storage"
    };
    (cargo) => {
        "Cargo"
    };
    (cargo_user) => {
        "Cargo User"
    };
    (dfs_api) => {
        "DFS API"
    };
}

#[macro_export]
macro_rules! build_mut_tuple {
    ($context:ident [] -> [$(,)? $($val:ident),*]) => {
        ($($context.$val.as_mut().unwrap()),*)
    };
    ($context:ident [$val:ident => None, $($tail:tt)*] -> [$($body:tt)*]) => {
        $crate::build_mut_tuple!($context [$($tail)*] -> [$($body)*])
    };
    ($context:ident [$val:ident => Some(_), $($tail:tt)*] -> [$($body:tt)*]) => {
        $crate::build_mut_tuple!($context [$($tail)*] -> [$($body)*, $val])
    };
}

#[macro_export]
macro_rules! build_ifs {
    ($context:ident [$val:ident => Some(_), $($pattern:tt)*] $callback:ident($($args:tt)*)) => {
        if $context.$val.is_none() {
            Err(anyhow::Error::msg(
                concat!($crate::field_to_string!($val), " should be set")
            ))
        } else { $crate::build_ifs!($context [$($pattern)*] $callback($($args)*)) }
    };
    ($context:ident [$val:ident => None, $($pattern:tt)*] $callback:ident($($args:tt)*)) => {
        if $context.$val.is_some() {
            Err(anyhow::Error::msg(
                concat!($crate::field_to_string!($val)," should not be set")
            ))
        } else { $crate::build_ifs!($context [$($pattern)*] $callback($($args)*)) }
    };
    ($context:ident [] $callback:ident($($args:tt)*)) => {
        Ok($crate::$callback!($context $($args)*))
    };
}

#[macro_export]
macro_rules! match_context {
    ($context:ident, $($pattern:tt)+) => {{
        $crate::build_ifs!($context [$($pattern)+,] build_mut_tuple([$($pattern)+,] -> []))
    }};
}