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
// MIT License
//
// Copyright (c) 2024 Robin Doer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

use anyhow::{anyhow, Result};
use is_executable::IsExecutable;
use log::{debug, error, trace, warn};
use nuts_tool_api::tool::Plugin;
use nuts_tool_api::tool_dir;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::{env, fs};

use crate::config::load_path;

fn find_in_path(relative: &Path) -> Option<Cow<Path>> {
    if let Some(path_env) = env::var_os("PATH") {
        trace!("PATH: {:?}", path_env);

        let abs_path = env::split_paths(&path_env)
            .map(|path| path.join(relative))
            .inspect(|path| trace!("testing {}", path.display()))
            .find(|path| path.exists());

        debug!("absolute path in PATH: {:?}", abs_path);

        abs_path.map(Cow::Owned)
    } else {
        warn!("no environment variable PATH found");
        None
    }
}

fn make_from_current_exe(relative: &Path) -> Result<Cow<Path>> {
    let cur_exe = env::current_exe()
        .map_err(|err| anyhow!("could not detect path of executable: {}", err))?;
    let path = cur_exe.with_file_name(relative.as_os_str());

    debug!("absolute path from current exe: '{}'", path.display());

    Ok(Cow::Owned(path))
}

#[derive(Debug, Deserialize, Serialize)]
struct Inner {
    path: PathBuf,
}

impl Inner {
    fn absolute_path(&self) -> Result<Cow<Path>> {
        if self.path.is_absolute() {
            Ok(Cow::Borrowed(self.path.as_path()))
        } else {
            match find_in_path(&self.path) {
                Some(path) => Ok(path),
                None => make_from_current_exe(&self.path),
            }
        }
    }

    fn validate(&self) -> bool {
        match self.absolute_path() {
            Ok(path) => Self::validate_path(&path),
            Err(err) => {
                error!("failed to validate {}: {}", self.path.display(), err);
                false
            }
        }
    }

    fn validate_path(path: &Path) -> bool {
        if !path.is_file() {
            error!("{}: not a file", path.display());
            return false;
        }

        if !path.is_executable() {
            error!("{}: not executable", path.display());
            return false;
        }

        let plugin = Plugin::new(path);

        if let Err(err) = plugin.info() {
            error!("{}: not a plugin ({})", path.display(), err);
            return false;
        }

        debug!("{}: is valid", path.display());

        true
    }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct PluginConfig {
    #[serde(flatten)]
    plugins: HashMap<String, Inner>,
}

impl PluginConfig {
    pub fn load() -> Result<PluginConfig> {
        match load_path(Self::config_file()?.as_path())? {
            Some(s) => Ok(toml::from_str(&s)?),
            None => Ok(PluginConfig {
                plugins: HashMap::new(),
            }),
        }
    }

    pub fn config_file() -> Result<PathBuf> {
        Ok(tool_dir()?.join("plugins"))
    }

    pub fn all_plugins(&self) -> Vec<&str> {
        let mut keys = self
            .plugins
            .iter()
            .filter(|(_, inner)| inner.validate())
            .map(|(name, _)| name.as_str())
            .collect::<Vec<&str>>();

        keys.sort();

        keys
    }

    pub fn have_plugin(&self, name: &str) -> bool {
        self.plugins
            .get(name)
            .filter(|inner| inner.validate())
            .is_some()
    }

    pub fn remove_plugin(&mut self, name: &str) -> bool {
        self.plugins.remove(name).is_some()
    }

    pub fn path(&self, name: &str) -> Result<Cow<Path>> {
        match self.plugins.get(name).filter(|inner| inner.validate()) {
            Some(inner) => inner.absolute_path(),
            None => Err(anyhow!("no such plugin: {}", name)),
        }
    }

    pub fn set_path<P: AsRef<Path>>(&mut self, name: &str, path: P) -> bool {
        let inner = Inner {
            path: path.as_ref().into(),
        };

        let valid = inner.validate();

        if valid {
            self.plugins.insert(name.to_string(), inner);
        }

        valid
    }

    pub fn save(&self) -> Result<()> {
        let path = Self::config_file()?;
        let toml = toml::to_string(self)?;

        debug!("{}: dump {} bytes", path.display(), toml.as_bytes().len());

        fs::write(path, toml)?;

        Ok(())
    }
}