summaryrefslogtreecommitdiff
path: root/src/delete.rs
blob: affbd8d19490f7bb12e74d73f950ae091e26ba85 (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
use std::fs;
use std::path::Path;
use colored::Colorize;
use std::process::Command;
use crate::install::{load_package, InstalledDB, Package, find_package_file};

const CRITICAL_ROLES: &[&str] = &["init-system", "sh"];

fn has_role(pkg_name: &str, role: &str) -> bool {
    load_package(pkg_name)
        .map(|p| p.provides.contains(&role.to_string()))
        .unwrap_or(false)
}

pub fn check_critical_removal(pkg_name: &str, db: &InstalledDB) -> Result<(), String> {
    let pkg = load_package(pkg_name).ok_or("Package info not found in repository")?;

    for &role in CRITICAL_ROLES {
        if !pkg.provides.contains(&role.to_string()) {
            continue;
        }
        let others = db.packages.values()
            .filter(|p| p.name != pkg_name && has_role(&p.name, role))
            .count();
        if others == 0 {
            return Err(format!(
                "{} CRITICAL: '{}' is your only provider of '{}'. Install an alternative first, or use --di to replace atomically.",
                "[ror]".red().bold(),
                pkg_name,
                role
            ));
        }
    }

    Ok(())
}

pub fn check_critical_removal_with_replacement(pkg_name: &str, replacement: &str, db: &InstalledDB) -> Result<(), String> {
    let pkg = load_package(pkg_name).ok_or("Package info not found in repository")?;
    let replacement_pkg = load_package(replacement).ok_or("Replacement package not found in repository")?;

    for &role in CRITICAL_ROLES {
        if !pkg.provides.contains(&role.to_string()) {
            continue;
        }
        let replacement_covers = replacement_pkg.provides.contains(&role.to_string());
        let other_installed = db.packages.values()
            .filter(|p| p.name != pkg_name && has_role(&p.name, role))
            .count();
        if !replacement_covers && other_installed == 0 {
            return Err(format!(
                "{} CRITICAL: removing '{}' would leave the system without a '{}' provider, and '{}' does not provide it.",
                "[ror]".red().bold(),
                pkg_name,
                role,
                replacement
            ));
        }
    }

    Ok(())
}

pub fn check_critical_install(pkg_name: &str, db: &InstalledDB) -> Result<(), String> {
    let pkg = load_package(pkg_name).ok_or("Package info not found in repository")?;

    for &role in CRITICAL_ROLES {
        if !pkg.provides.contains(&role.to_string()) {
            continue;
        }
        if let Some(existing) = db.packages.values().find(|p| has_role(&p.name, role)) {
            return Err(format!(
                "{} CRITICAL: '{}' provides '{}', but '{}' already provides it. Use --di {} {} to replace it atomically.",
                "[ror]".red().bold(),
                pkg_name,
                role,
                existing.name,
                existing.name,
                pkg_name
            ));
        }
    }

    Ok(())
}

pub fn remove_package_files_only(pkg_name: &str, files: &[String]) -> bool {
    let mut failed = false;

    for rel_path in files {
        let full_path = Path::new("/").join(rel_path);
        if full_path.exists() {
            if let Err(e) = fs::remove_file(&full_path) {
                eprintln!("{} Failed to remove {}: {}", "[ror]".red().bold(), full_path.display(), e);
                failed = true;
            } else {
                println!("{} Removed {}", ">>>".green(), full_path.display());
            }
        }
    }

    if let Some(pkg_path) = find_package_file(pkg_name) {
        if let Ok(content) = fs::read_to_string(pkg_path) {
            if let Ok(pkg) = serde_yaml::from_str::<Package>(&content) {
                if !pkg.delete_steps.trim().is_empty() {
                    println!("{} Running delete steps for '{}'...", ">>>".yellow(), pkg_name);
                    let status = Command::new("sh")
                        .arg("-c")
                        .arg(&pkg.delete_steps)
                        .status()
                        .expect("Failed to execute delete steps");
                    if !status.success() {
                        eprintln!("{} Delete steps for '{}' failed", "[ror]".red().bold(), pkg_name);
                        failed = true;
                    }
                }
            }
        }
    }

    !failed
}

pub fn remove_package(pkg_name: &str) {
    let mut db = InstalledDB::load();

    let files: Vec<String> = match db.packages.get(pkg_name) {
        Some(r) => r.files.iter().cloned().collect(),
        None => {
            eprintln!("{} Package '{}' is not installed.", "[ror]".red().bold(), pkg_name);
            return;
        }
    };

    if let Err(e) = check_critical_removal(pkg_name, &db) {
        eprintln!("{}", e);
        return;
    }

    println!("{} Removing package '{}'...", "[ror]".blue().bold(), pkg_name);

    let success = remove_package_files_only(pkg_name, &files);

    db.packages.remove(pkg_name);
    if let Err(e) = db.save() {
        eprintln!("{} Failed to update installed DB: {}", "[ror]".red().bold(), e);
    } else {
        println!("{} Package '{}' removed from database.", "[ror]".green(), pkg_name);
    }

    if !success {
        eprintln!("{} Some errors occurred while removing '{}'.", "[ror]".red().bold(), pkg_name);
    } else {
        println!("{} Package '{}' successfully removed.", "[ror]".green().bold(), pkg_name);
    }
}