summaryrefslogtreecommitdiff
path: root/src/pkgtoolkit/pkgtools.rs
blob: 1577a504a66220e52d348020022665308f919d80 (plain)
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
use crate::cfg::config::Config;
use std::{io, 
          fs::{self, File, create_dir_all},
          str, 
          path::Path}; 
          
// use emissary_core::i2np::tunnel::build;
use flate2::read::GzDecoder;
use serde::{Deserialize, Serialize};
use tar::Archive;
use toml; 

#[derive(Serialize, Debug, Deserialize)]
pub enum archs {
    X86_64,
    Aarch64,
    X86,
}

#[derive(Serialize, Debug, Deserialize)]
pub struct Package {
    name: String, 
    version: String, 
    arch: archs, 
    descr: Option<String>,
}

#[derive(Deserialize, Debug)]
struct Install {
    package: Package,
    path: String, 
    user: String, 
    group: String, 
    mode: String,
    //. Cancels the previous fields and installs them using the shell script
    custom_script: Option<String>,
}

#[derive(Deserialize, Debug)]
struct Setts {
    env: Option<String>, // Export environment variables if this needed 
    test: Option<String>, // Test the package after installation
}

#[derive(Deserialize, Serialize, Debug)]
pub enum BuildSystems {
    Make,
    CMake,
    Meson, 
    Cargo
}

#[derive(Deserialize, Debug)]
struct Build {
    build_system: BuildSystems, 
    env: Option<String>,
    script: Option<String>,
}

impl Package { 
    /// Load meta information from the .mesk archive.
    ///
    /// This function parses the meta information from the .mesk archive,
    /// which includes the package name, version, architecture, description,
    /// installation path, user, group, mode, and custom installation script 
    /// and deserializing this information. Returns (Install, Option<Setts>, Option<Build>)
    /// 
    /// The function expects the 'INSTALL', 'SETTS', and 'BUILD' files to be present
    /// in the `config.paths.cache_dir`. It specifically requires the 'INSTALL' file.
    /// 
    /// # Errors
    ///
    /// Returns an error if the `cache_dir` cannot be created, if the required 'INSTALL' file
    /// is not found, or if the 'INSTALL' file is empty.
    fn loadmeta(minimal_package_meta: Package) -> Result<(Install, Option<Setts>, Option<Build>), Box<dyn std::error::Error>> { // Changed return type for more flexibility
        /* 
                Example INSTALL format: 
                [package]
                name = "my-package"
                version = "1.0.0"
                arch = "X86_64"
                descr = "Just example INSTALL script"

                [install]
                path = "/usr/bin/my-package"
                user = "root"
                group = "root"
                mode = "755"

                # Also [install] can be 
                # path = "/usr/bin/my-package"
                # user = "root"
                # group = "root"
                # mode = "755"
                # custom_script = "./install.sh" OR 
                # custom_script = """
                #     echo "Installing my-package"
                #     sudo apt-get install my-package
                # """
        */


        let config = Config::parse()?; // Propagate error if parsing fails

        // Ensure the cache directory exists
        fs::create_dir_all(&config.paths.cache_dir)?;


        let cache_dir = &config.paths.cache_dir;
        let install_path = Path::new(cache_dir).join(format!("{}/INSTALL", minimal_package_meta.name));
        let setts_path = Path::new(cache_dir).join(format!("{}/SETTS", minimal_package_meta.name));
        let build_path = Path::new(cache_dir).join(format!("{}/BUILD", minimal_package_meta.name));

        // Check for required 'INSTALL' file
        if !install_path.exists() {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "File INSTALL not found in cache directory"
            ).into()); // Convert to Box<dyn Error>
        }

        // Read and deserialize the INSTALL file
        let install_content = fs::read_to_string(&install_path)?;
        let install_meta: Install = toml::from_str(&install_content)?;

        // Initialize optional structures as None
        let mut setts_meta: Option<Setts> = None;
        let mut build_meta: Option<Build> = None;

        // Attempt to read and deserialize the SETTS file if it exists
        if setts_path.exists() {
            let setts_content = fs::read_to_string(&setts_path)?;
            setts_meta = Some(toml::from_str(&setts_content)?);
        }

        // Attempt to read and deserialize the BUILD file if it exists
        if build_path.exists() {
            let build_content = fs::read_to_string(&build_path)?;
            build_meta = Some(toml::from_str(&build_content)?);
        }

        // Log if custom script is present
        if let Some(ref script) = install_meta.custom_script {
            println!("Custom script found for package: {}", install_meta.package.name);
            // Consider logging the script content or just its presence based on verbosity
            // e.g., log::debug!("Custom script content: {}", script);
        } else {
            println!("No custom script for package: {}", install_meta.package.name);
        }

        Ok((install_meta, setts_meta, build_meta))
    }
    
    

    /// Checks if the archive contains INSTALL, SETTS and BUILD files.
    ///
    /// Checks if INSTALL file exists and is not empty. If it does not exist or is empty, returns an error.
    ///
    /// Checks if SETTS and BUILD files exist and are not empty. If they do not exist or are empty, logs a warning.
    /// # Errors 
    /// * Returns an error if INSTALL file does not exist or is empty.
    /// * Returns an error if INSTALL file is empty.
    ///
    // TODO: Add meta-files validation here. 
    pub fn check(path_to_archive: String) -> Result<bool, std::io::Error> {
        let config: Config = Config::parse().unwrap(); 

        create_dir_all(&config.paths.cache_dir)?;

        let file = File::open(&path_to_archive)?;
        let gz = GzDecoder::new(file);
        let mut archive = Archive::new(gz);

        archive.unpack(&config.paths.cache_dir)?;

        let install_path = Path::new(&config.paths.cache_dir).join("INSTALL");
        let setts_path = Path::new(&config.paths.cache_dir).join("SETTS");
        let build_path = Path::new(&config.paths.cache_dir).join("BUILD");

        if !install_path.exists() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "INSTALL file not found in archive",
            ));
        }

        let install_content = std::fs::read_to_string(&install_path)?;
        if install_content.trim().is_empty() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "INSTALL file is empty",
            ));
        }

        if !setts_path.exists() {
            log::warn!("SETTS file not found in archive. Make sure you dont need this.");
        } else {
            let setts_content = std::fs::read_to_string(&setts_path)?;
            if setts_content.trim().is_empty() {
                log::warn!("SETTS file is empty. Make sure you dont need this.");
            }
        }

        if !build_path.exists() {
            log::warn!("BUILD file not found in archive. Make sure you dont need this.");
        } else {
            let build_content = std::fs::read_to_string(&build_path)?;
            if build_content.trim().is_empty() {
                log::warn!("BUILD file is empty. Make sure you dont need this.");
            }
        }

        Ok(true)
    }

    pub fn build() -> Result<bool, std::io::Error> {
        todo!();  
    }
    pub fn install() -> Result<bool, std::io::Error> {
        todo!(); 
    } 
    pub fn gen_index() -> Result<bool, std::io::Error> {    
        todo!();

    }
}