1
use std::path::{
2
  Path,
3
  PathBuf,
4
};
5

            
6
use mk_lib::schema::TaskRoot;
7
use mk_lib::secrets::{
8
  resolve_secret_config,
9
  SecretBackend,
10
  SecretConfig,
11
  SecretSettings,
12
};
13

            
14
pub(super) struct Context {
15
  settings: SecretSettings,
16
  base_dir: PathBuf,
17
  root_settings: Option<SecretSettings>,
18
  active_config_path: Option<PathBuf>,
19
}
20

            
21
impl Context {
22
  pub fn new(task_root: &TaskRoot) -> Self {
23
    Self {
24
      settings: SecretSettings::default(),
25
      base_dir: task_root.config_base_dir(),
26
      root_settings: task_root.normalized_secret_settings(),
27
      active_config_path: task_root.source_path.clone(),
28
    }
29
  }
30

            
31
  pub fn set_keys_location(&mut self, keys_location: &str) {
32
    self.settings.keys_location = Some(keys_location.to_string());
33
  }
34

            
35
  pub fn set_vault_location(&mut self, vault_location: &str) {
36
    self.settings.vault_location = Some(vault_location.to_string());
37
  }
38

            
39
  pub fn set_key_name(&mut self, key_name: &str) {
40
    self.settings.key_name = Some(key_name.to_string());
41
    self.settings.backend = Some(SecretBackend::BuiltInPgp);
42
  }
43

            
44
  pub fn set_gpg_key_id(&mut self, gpg_key_id: &str) {
45
    self.settings.gpg_key_id = Some(gpg_key_id.to_string());
46
    self.settings.backend = Some(SecretBackend::Gpg);
47
  }
48

            
49
  pub fn settings(&self) -> &SecretSettings {
50
    &self.settings
51
  }
52

            
53
  pub fn resolved_config(&self) -> SecretConfig {
54
    self.resolve_with_settings(&self.settings)
55
  }
56

            
57
  pub fn resolve_with_settings(&self, settings: &SecretSettings) -> SecretConfig {
58
    resolve_secret_config(&self.base_dir, Some(settings), None, self.root_settings.as_ref())
59
  }
60

            
61
  pub fn active_config_path(&self) -> Option<&Path> {
62
    self.active_config_path.as_deref()
63
  }
64

            
65
  pub fn config_base_dir(&self) -> &Path {
66
    &self.base_dir
67
  }
68

            
69
  pub fn root_settings(&self) -> Option<&SecretSettings> {
70
    self.root_settings.as_ref()
71
  }
72

            
73
  pub fn keys_location(&self) -> String {
74
    self.resolved_config().keys_location.to_string_lossy().to_string()
75
  }
76

            
77
  pub fn vault_location(&self) -> String {
78
    self
79
      .resolved_config()
80
      .vault_location
81
      .to_string_lossy()
82
      .to_string()
83
  }
84

            
85
  pub fn key_name(&self) -> String {
86
    self.resolved_config().key_name
87
  }
88
}