summaryrefslogtreecommitdiff
path: root/src/pkgtoolkit/pkgtools.rs
blob: 9fe01c6fa3d4443ebbb15e764e4e524f8109848d (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
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
// I think I should split this file into a few smaller ones.

use crate::cfg::config::Config;
use std::{
    fs::{self, File, create_dir_all},
    io,
    os::unix::fs::PermissionsExt,
    path::Path,
    process::Command,
    str,
};

// use emissary_core::i2np::tunnel::build;

use flate2::read::GzDecoder;
use serde::{Deserialize, Serialize};
use tar::Archive;
use toml;

#[derive(Serialize, Debug, Deserialize, Clone)]
pub enum Archs {
    X86_64,
    Aarch64,
    X86,
    ArmV7,
    ArmV8,
}

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

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

#[allow(dead_code)]
#[derive(Deserialize, Debug, Clone)]
struct Install {
    package: Package,
    install: InstallMeta,
}

#[allow(dead_code)]
#[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,
}

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

impl Archs {
    fn as_str(&self) -> &'static str {
        match self {
            Archs::X86_64 => "x86_64",
            Archs::Aarch64 => "aarch64",
            Archs::X86 => "x86",
            Archs::ArmV7 => "armv7",
            Archs::ArmV8 => "armv8",
        }
    }
}

#[allow(dead_code)]
impl Package {
    /// Execute the build script for the package.
    ///
    /// This function takes the `Build` meta information as an argument and
    /// executes the build script accordingly. It also handles the different
    /// build systems supported (Make, CMake, Meson, Cargo).
    ///
    /// # Errors
    ///
    /// Returns an error if the build command fails.
    fn execute_build(&self, build_meta: &Build) -> Result<(), std::io::Error> {
        let config = Config::parse().map_err(|e| std::io::Error::other(e.to_string()))?;
        let build_dir =
            Path::new(&config.paths.cache_dir).join(format!("{}-{}", self.name, self.version));

        let mut cmd = match build_meta.build_system {
            BuildSystems::Make => {
                let mut c = Command::new("make");
                c.current_dir(&build_dir);
                if build_meta.script.is_some() {
                    c.arg("-f").arg(build_meta.script.as_ref().unwrap());
                }
                c.arg("all");
                c
            }
            BuildSystems::CMake => {
                let build_dir_build = build_dir.join("build");
                create_dir_all(&build_dir_build)?;
                let mut c = Command::new("cmake");
                c.arg("-S")
                    .arg(&build_dir)
                    .arg("-B")
                    .arg(&build_dir_build)
                    .current_dir(&build_dir);
                c
            }
            BuildSystems::Meson => {
                let build_dir_build = build_dir.join("build");
                create_dir_all(&build_dir_build)?;
                let mut c = Command::new("meson");
                c.arg("setup").arg(&build_dir_build).current_dir(&build_dir);
                c
            }
            BuildSystems::Cargo => {
                let mut c = Command::new("cargo");
                c.arg("build").arg("--release").current_dir(&build_dir);
                c
            }
        };

        let output = cmd
            .output()
            .map_err(|e| std::io::Error::other(format!("Build command failed: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(std::io::Error::other(format!("Build failed:\n{}", stderr)));
        }

        Ok(())
    }

    /// Extracts a .tar.gz archive to the cache directory specified in Config.
    ///
    /// This function handles opening the archive file, decompressing it with GzDecoder,
    /// and unpacking the contents into the configured cache directory.
    ///
    /// # Arguments
    /// * `path_to_archive` - A string representing the path to the .tar.gz file.
    ///
    /// # Returns
    /// * `Ok(())` if the archive is successfully unpacked.
    /// * `Err(std::io::Error)` if there's an issue opening, reading, or unpacking the archive.
    pub fn extract_archive(path_to_archive: &str) -> Result<(), std::io::Error> {
        let 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);

        // Unpack directly into the cache directory
        archive.unpack(&config.paths.cache_dir)?;
        Ok(())
    }

    /// 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.
    #[allow(clippy::type_complexity)]
    fn loadmeta(
        minimal_package_meta: &mut Self,
    ) -> 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.install.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> {
        // Call the new extraction function
        Self::extract_archive(&path_to_archive)?;

        let config = Config::parse().unwrap();

        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.");
            }
        }

        let content = std::fs::read_to_string(&install_path).map_err(|e| {
            log::warn!("Failed to read file: {}", e);
            e
        })?;
        let install_content: Result<Install, toml::de::Error> = toml::from_str(&content);

        log::info!("Validating arch...");
        if std::env::consts::ARCH
            != install_content
                .as_ref()
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?
                .package
                .arch
                .as_str()
        {
            let pkg_arch = &install_content.unwrap().package.arch; // Safe because of previous check/unwrap
            log::error!(
                "Arch mismatch. Package arch: {:?}, Host arch: {}",
                pkg_arch,
                std::env::consts::ARCH
            );
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Arch mismatch",
            ));
        }

        Ok(true)
    }

    /// Builds the package according to the BUILD file in the archive.
    ///
    /// There are two strategies for building the package. If the BUILD file is empty, the package is assumed to be a binary package and the default install hook is skipped. If the BUILD file is not empty, the package is assumed to be a source package and the default build hook is skipped.
    ///
    /// If the BUILD file is empty and the INSTALL file contains a custom script, the custom script is run instead of the default install hook.
    /// If the BUILD file is not empty and the INSTALL file contains a custom script, the custom script is ignored.
    ///
    ///
    /// # Errors
    ///
    /// Returns an error if the BUILD file is invalid or if the build or install hook fails.
    pub fn build(&mut self) -> Result<bool, std::io::Error> {
        let meta = Self::loadmeta(self).unwrap();
        let install_meta = meta.0;
        // let setts_meta = meta.1;
        let build_meta = meta.2;

        // BUILD NOT EMPTY. SOURCE: -> BUILD -> INSTALL -> SETTS
        // BUILD EMPTY. BIN: -> INSTALL -> SETTS
        enum Strategies {
            Bin,
            Source,
        }

        let strategy; //default

        if build_meta.is_none() {
            log::info!("BUILD file is empty. Skipping build, preparing to install");
            strategy = Strategies::Bin;
        } else {
            strategy = Strategies::Source;
            log::info!("BUILD file is not empty. Skipping install, preparing to build");
        }

        match strategy {
            Strategies::Bin => {
                if install_meta.install.custom_script.is_none() {
                    log::info!("Strategy: BIN; No custom script. Running default install hook.");
                } else {
                    log::info!("Strategy: BIN; Running custom script.");
                    let script = install_meta.install.custom_script.as_ref().unwrap();
                    if !script.starts_with("./") {
                        let _output = std::process::Command::new(script);
                    } else {
                        let _output = std::process::Command::new(format!("/bin/sh '{}'", script));
                    }
                }
            }
            Strategies::Source => {
                log::info!("Strategy: SOURCE; Running default build hook.");
                let _ = self.execute_build(&build_meta.unwrap());
            }
        }

        Ok(true)
    }

    /// Installs the package according to the INSTALL file in the archive.
    ///
    /// There are two strategies for installing the package. If the BUILD file is empty, the package is assumed to be a binary package and the default install hook is skipped. If the BUILD file is not empty, the package is assumed to be a source package and the default build hook is skipped.
    ///
    /// If the BUILD file is empty and the INSTALL file contains a custom script, the custom script is run instead of the default install hook.
    /// If the BUILD file is not empty and the INSTALL file contains a custom script, the custom script is ignored.
    ///
    /// # Errors
    ///
    /// Returns an error if the BUILD file is invalid or if the build or install hook fails.
    pub fn install(&mut self) -> Result<bool, std::io::Error> {
        let config = Config::parse().map_err(|e| std::io::Error::other(e.to_string()))?;
        let (install_meta, _setts_meta, build_meta) =
            Self::loadmeta(self).map_err(|e| std::io::Error::other(e.to_string()))?;

        let is_build_present_and_not_empty = build_meta.is_some();

        if is_build_present_and_not_empty {
            log::info!(
                "Found BUILD file, preparing to build and install package: {}",
                self.name
            );
            let build_meta_ref = build_meta.as_ref().unwrap();
            let _ = self.execute_build(build_meta_ref);

            if matches!(build_meta_ref.build_system, BuildSystems::Make) {
                log::info!("Running 'make install' for package: {}", self.name);
                let build_dir = Path::new(&config.paths.cache_dir)
                    .join(format!("{}-{}", self.name, self.version));
                let output = Command::new("make")
                    .arg("install")
                    .current_dir(&build_dir)
                    .output()
                    .map_err(|e| std::io::Error::other(format!("'make install' failed: {}", e)))?;

                if !output.status.success() {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    return Err(std::io::Error::other(format!(
                        "'make install' failed:\n{}",
                        stderr
                    )));
                }
            }
        } else {
            log::info!(
                "No BUILD file or it's empty. Treating as binary package. Installing via INSTALL config or custom script."
            );
            // Установка бинарного пакета
            if let Some(ref script) = install_meta.install.custom_script {
                log::info!(
                    "Executing custom install script for {}",
                    install_meta.package.name
                );
                let status = if script.starts_with("./") || script.contains('/') {
                    Command::new("/bin/sh").arg("-c").arg(script).status()
                } else {
                    Command::new(script).status()
                }
                .map_err(|e| {
                    std::io::Error::other(format!("Failed to run custom script: {}", e))
                })?;

                if !status.success() {
                    return Err(std::io::Error::other("Custom install script failed"));
                }
            } else {
                log::info!(
                    "No custom script. Running default install hook for {}",
                    install_meta.package.name
                );
                let source_file_name = &self.name;
                let build_dir = Path::new(&config.paths.cache_dir)
                    .join(format!("{}-{}", self.name, self.version));
                let src_path = build_dir.join(source_file_name);
                let dest_path = Path::new(&install_meta.install.path);

                if let Some(parent) = dest_path.parent() {
                    create_dir_all(parent).map_err(|e| {
                        std::io::Error::other(format!("Failed to create parent dir: {}", e))
                    })?;
                }

                fs::copy(&src_path, dest_path)
                    .map_err(|e| std::io::Error::other(format!("Failed to copy file: {}", e)))?;

                let mode = u32::from_str_radix(&install_meta.install.mode, 8).map_err(|_| {
                    std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "Invalid mode string in INSTALL",
                    )
                })?;
                let perms = PermissionsExt::from_mode(mode);
                fs::set_permissions(dest_path, perms).map_err(|e| {
                    std::io::Error::other(format!("Failed to set permissions: {}", e))
                })?;

                let output = Command::new("chown")
                    .arg(format!(
                        "{}:{}",
                        install_meta.install.user, install_meta.install.group
                    ))
                    .arg(dest_path)
                    .output()
                    .map_err(|e| std::io::Error::other(format!("'chown' command failed: {}", e)))?;

                if !output.status.success() {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    log::warn!(
                        "Warning: 'chown' command failed (requires root?):\n{}",
                        stderr
                    );
                }
            }
        }

        log::info!("Package {} installed successfully.", self.name);
        Ok(true)
    }
    pub fn gen_index() -> Result<bool, std::io::Error> {
        todo!();
    }
}