Skip to main content

carch_cli/
commands.rs

1use carch_core::error::{CarchError, Result};
2use carch_core::version;
3use log::info;
4use serde_json::Value;
5use std::fs;
6use std::io::{self, Write};
7use std::process::{Command, Stdio};
8use tempfile::Builder;
9
10pub fn check_for_updates() -> Result<()> {
11    println!("Checking for updates...");
12
13    let current_version = version::current_version();
14
15    match version::get_latest_version() {
16        Ok(latest_version) => {
17            println!("Current version: {current_version}");
18            println!("Latest version: {latest_version}");
19
20            if latest_version == current_version {
21                println!("\nYou are using the latest version of Carch.");
22            } else {
23                println!("\nUpdate available!");
24                println!("Run 'carch update' to update to the latest version.");
25            }
26        }
27        Err(e) => {
28            eprintln!("Error checking for updates: {e}");
29            return Err(e);
30        }
31    }
32
33    Ok(())
34}
35
36enum Distro {
37    Termux,
38    Arch,
39    Fedora,
40    OpenSuse,
41}
42
43fn is_termux() -> bool {
44    std::env::var("TERMUX_VERSION").is_ok()
45        || std::path::Path::new("/data/data/com.termux").exists()
46}
47
48fn detect_distro() -> Result<Distro> {
49    if is_termux() {
50        return Ok(Distro::Termux);
51    }
52    if command_exists("pacman") {
53        return Ok(Distro::Arch);
54    }
55    if command_exists("dnf") {
56        return Ok(Distro::Fedora);
57    }
58    if command_exists("zypper") {
59        return Ok(Distro::OpenSuse);
60    }
61    Err(CarchError::Command(
62        "Unsupported distribution. Carch supports Arch, Fedora, openSUSE, and Termux.".into(),
63    ))
64}
65
66fn detect_termux_arch() -> Result<&'static str> {
67    let out = Command::new("uname").arg("-m").output()?;
68    let arch = String::from_utf8_lossy(&out.stdout);
69    let arch = arch.trim();
70    match arch {
71        "aarch64" | "arm64" => Ok("aarch64"),
72        a if a.starts_with("armv7") || a == "armv8l" || a == "arm" => Ok("arm"),
73        other => Err(CarchError::Command(format!("Unsupported Termux architecture: {other}"))),
74    }
75}
76
77fn command_exists(command: &str) -> bool {
78    Command::new("sh")
79        .arg("-c")
80        .arg(format!("command -v {command}"))
81        .stdout(Stdio::null())
82        .stderr(Stdio::null())
83        .status()
84        .is_ok_and(|s| s.success())
85}
86
87fn run_command(command: &mut Command) -> Result<()> {
88    let status = command.status()?;
89    if !status.success() {
90        return Err(CarchError::Command(format!("Command failed with exit code {status}")));
91    }
92    Ok(())
93}
94
95// Find the first release asset whose name ends with `asset_pattern`.
96fn get_latest_release_url(asset_pattern: &str) -> Result<String> {
97    let client = reqwest::blocking::Client::builder().user_agent("carch-cli").build()?;
98    let body: Value =
99        client.get("https://api.github.com/repos/harilvfs/carch/releases/latest").send()?.json()?;
100
101    let assets = body
102        .get("assets")
103        .and_then(Value::as_array)
104        .ok_or_else(|| CarchError::Command("Latest release has no 'assets' field".to_string()))?;
105
106    for asset in assets {
107        let name = asset.get("name").and_then(Value::as_str).unwrap_or("");
108        let url = asset.get("browser_download_url").and_then(Value::as_str).unwrap_or("");
109        if !url.is_empty() && name.ends_with(asset_pattern) {
110            return Ok(url.to_string());
111        }
112    }
113
114    Err(CarchError::Command(format!("Could not find release asset matching '{asset_pattern}'")))
115}
116
117fn termux_install_deb(deb_arch: &str) -> Result<()> {
118    println!("==> Fetching latest .deb package for {deb_arch}...");
119
120    let pattern = format!("_{deb_arch}.deb");
121    let deb_url = get_latest_release_url(&pattern)?;
122
123    let tmp_dir = std::env::var("PREFIX").map_or_else(|_| "/tmp".into(), |p| format!("{p}/tmp"));
124
125    let mut tmp_deb = Builder::new().prefix("carch_").suffix(".deb").tempfile_in(&tmp_dir)?;
126
127    println!("==> Downloading .deb package...");
128    let bytes = reqwest::blocking::get(&deb_url)?.bytes()?;
129    tmp_deb.write_all(&bytes)?;
130
131    let tmp_path = tmp_deb.path().to_path_buf();
132
133    println!("==> Installing .deb package...");
134    run_command(Command::new("dpkg").arg("-i").arg(&tmp_path))?;
135
136    let _ = fs::remove_file(&tmp_path);
137    Ok(())
138}
139
140fn install_for_distro(distro: &Distro) -> Result<()> {
141    match distro {
142        Distro::Termux => {
143            let arch = detect_termux_arch()?;
144            println!("==> Detected Termux architecture: {arch}");
145            termux_install_deb(arch)
146        }
147        Distro::Arch => {
148            println!("==> Cloning PKGBUILD...");
149            let home = std::env::var("HOME")
150                .map_err(|_| CarchError::Command("$HOME is not set".into()))?;
151            let pkgs_dir = std::path::PathBuf::from(home).join("pkgs");
152
153            if pkgs_dir.exists() {
154                fs::remove_dir_all(&pkgs_dir)?;
155            }
156
157            run_command(
158                Command::new("git")
159                    .arg("clone")
160                    .arg("https://github.com/carch-org/pkgs")
161                    .arg(&pkgs_dir)
162                    .stdout(Stdio::null())
163                    .stderr(Stdio::null()),
164            )?;
165
166            let carch_bin_dir = pkgs_dir.join("carch-bin");
167            run_command(
168                Command::new("makepkg").arg("-si").arg("--noconfirm").current_dir(&carch_bin_dir),
169            )
170        }
171        Distro::Fedora | Distro::OpenSuse => {
172            println!("==> Downloading carch RPM...");
173            let rpm_url = get_latest_release_url(".rpm")?;
174
175            let bytes = reqwest::blocking::get(&rpm_url)?.bytes()?;
176            let rpm_path = std::path::PathBuf::from("/tmp/carch.rpm");
177            fs::write(&rpm_path, &bytes)?;
178
179            match distro {
180                Distro::Fedora => run_command(
181                    Command::new("sudo").arg("dnf").arg("install").arg("-y").arg(&rpm_path),
182                ),
183                Distro::OpenSuse => run_command(
184                    Command::new("sudo")
185                        .arg("zypper")
186                        .arg("install")
187                        .arg("-y")
188                        .arg("--allow-unsigned-rpm")
189                        .arg(&rpm_path),
190                ),
191                _ => unreachable!(),
192            }
193        }
194    }
195}
196
197fn uninstall_for_distro(distro: &Distro) -> Result<()> {
198    match distro {
199        Distro::Termux => {
200            let installed = Command::new("dpkg")
201                .args(["-s", "carch"])
202                .stdout(Stdio::null())
203                .stderr(Stdio::null())
204                .status()
205                .is_ok_and(|s| s.success());
206
207            if installed {
208                run_command(Command::new("dpkg").arg("-r").arg("carch"))?;
209                println!("==> carch has been removed.");
210            } else {
211                println!("==> carch is not installed.");
212            }
213            Ok(())
214        }
215        Distro::Arch => run_command(
216            Command::new("sudo")
217                .arg("pacman")
218                .arg("-R")
219                .arg("carch-bin")
220                .arg("carch-bin-debug")
221                .arg("--noconfirm"),
222        ),
223        Distro::Fedora => {
224            run_command(Command::new("sudo").arg("dnf").arg("remove").arg("carch").arg("-y"))
225        }
226        Distro::OpenSuse => {
227            run_command(Command::new("sudo").arg("zypper").arg("remove").arg("-y").arg("carch"))
228        }
229    }
230}
231
232enum InstallMethod {
233    Cargo,
234    InstallScript,
235}
236
237fn get_install_method() -> Result<InstallMethod> {
238    print!("Installed via (c)argo or (i)nstall script? ");
239    io::stdout().flush()?;
240    let mut choice = String::new();
241    io::stdin().read_line(&mut choice)?;
242    match choice.trim().to_lowercase().as_str() {
243        "c" | "cargo" => Ok(InstallMethod::Cargo),
244        "i" | "install script" => Ok(InstallMethod::InstallScript),
245        _ => Err(CarchError::Command("Invalid choice. Please run the command again.".into())),
246    }
247}
248
249pub fn update() -> Result<()> {
250    if !command_exists("carch") {
251        println!("Carch is not installed. Please install it first.");
252        return Ok(());
253    }
254
255    info!("Starting update...");
256    println!("==> Updating carch...");
257
258    match get_install_method()? {
259        InstallMethod::Cargo => {
260            run_command(Command::new("cargo").arg("install").arg("carch-cli").arg("--force"))?;
261        }
262        InstallMethod::InstallScript => {
263            let distro = detect_distro()?;
264            install_for_distro(&distro)?;
265        }
266    }
267
268    println!("Update done.");
269    Ok(())
270}
271
272pub fn uninstall() -> Result<()> {
273    if !command_exists("carch") {
274        println!("Carch is not installed.");
275        return Ok(());
276    }
277
278    info!("Starting uninstall...");
279
280    match get_install_method()? {
281        InstallMethod::Cargo => {
282            run_command(Command::new("cargo").arg("uninstall").arg("carch-cli"))?;
283        }
284        InstallMethod::InstallScript => {
285            let distro = detect_distro()?;
286            uninstall_for_distro(&distro)?;
287        }
288    }
289
290    println!("Uninstallation done.");
291    Ok(())
292}