1use carch_core::error::{CarchError, Result};
2use carch_core::version;
3use log::info;
4use std::fs;
5use std::io::{self, Write};
6use std::path::Path;
7use std::process::{Command, Stdio};
8
9pub fn check_for_updates() -> Result<()> {
10 println!("Checking for updates...");
11
12 let current_version = version::current_version();
13
14 match version::get_latest_version() {
15 Ok(latest_version) => {
16 println!("Current version: {current_version}");
17 println!("Latest version: {latest_version}");
18
19 if latest_version == current_version {
20 println!("\nYou are using the latest version of Carch.");
21 } else {
22 println!("\nUpdate available!");
23 println!("Run 'carch update' to update to the latest version.");
24 }
25 }
26 Err(e) => {
27 eprintln!("Error checking for updates: {e}");
28 return Err(e);
29 }
30 }
31
32 Ok(())
33}
34
35fn command_exists(command: &str) -> bool {
36 Command::new("sh")
37 .arg("-c")
38 .arg(format!("command -v {command}"))
39 .stdout(Stdio::null())
40 .stderr(Stdio::null())
41 .status()
42 .is_ok_and(|s| s.success())
43}
44
45fn run_command(command: &mut Command) -> Result<()> {
46 let status = command.status()?;
47 if !status.success() {
48 return Err(CarchError::Command(format!("Command failed with exit code {status}")));
49 }
50 Ok(())
51}
52
53fn run_install_script() -> Result<()> {
54 let response = reqwest::blocking::get(
55 "https://raw.githubusercontent.com/harilvfs/carch/main/scripts/install.sh",
56 )
57 .and_then(|r| r.error_for_status())
58 .map_err(|e| CarchError::Command(format!("Failed to download install script: {e}")))?;
59
60 let script = response
61 .text()
62 .map_err(|e| CarchError::Command(format!("Failed to read install script: {e}")))?;
63
64 let mut child = Command::new("sh")
65 .stdin(Stdio::piped())
66 .spawn()
67 .map_err(|e| CarchError::Command(format!("Failed to run install script: {e}")))?;
68
69 use std::io::Write;
70 child
71 .stdin
72 .take()
73 .ok_or_else(|| CarchError::Command("Failed to pipe install script".into()))?
74 .write_all(script.as_bytes())
75 .map_err(|e| CarchError::Command(format!("Failed to pipe install script: {e}")))?;
76
77 let status =
78 child.wait().map_err(|e| CarchError::Command(format!("Install script failed: {e}")))?;
79
80 if !status.success() {
81 return Err(CarchError::Command(
82 "Install script failed. Try manually: curl -fsSL chalisehari.com.np/carch | sh -s -- install".into(),
83 ));
84 }
85 Ok(())
86}
87
88enum InstallMethod {
89 Cargo,
90 CargoBinstall,
91 InstallScript,
92}
93
94fn get_install_method() -> Result<InstallMethod> {
95 print!("Installed via (c)argo, (b)install, or (i)nstall script? ");
96 io::stdout().flush()?;
97 let mut choice = String::new();
98 io::stdin().read_line(&mut choice)?;
99 match choice.trim().to_lowercase().as_str() {
100 "c" | "cargo" => Ok(InstallMethod::Cargo),
101 "b" | "binstall" | "cargo-binstall" => Ok(InstallMethod::CargoBinstall),
102 "i" | "install script" => Ok(InstallMethod::InstallScript),
103 _ => Err(CarchError::Command("Invalid choice. Please run the command again.".into())),
104 }
105}
106
107fn get_install_method_for_uninstall() -> Result<InstallMethod> {
108 print!("Installed via (c)argo or (i)nstall script? ");
109 io::stdout().flush()?;
110 let mut choice = String::new();
111 io::stdin().read_line(&mut choice)?;
112 match choice.trim().to_lowercase().as_str() {
113 "c" | "cargo" => Ok(InstallMethod::Cargo),
114 "i" | "install script" => Ok(InstallMethod::InstallScript),
115 _ => Err(CarchError::Command("Invalid choice. Please run the command again.".into())),
116 }
117}
118
119pub fn update() -> Result<()> {
120 if !command_exists("carch") {
121 println!("Carch is not installed. Please install it first.");
122 return Ok(());
123 }
124
125 info!("Starting update...");
126 println!("Updating carch...");
127
128 match get_install_method()? {
129 InstallMethod::Cargo => {
130 run_command(Command::new("cargo").arg("install").arg("carch-cli").arg("--force"))?;
131 }
132 InstallMethod::CargoBinstall => {
133 run_command(Command::new("cargo").arg("binstall").arg("carch-cli").arg("--force"))?;
134 }
135 InstallMethod::InstallScript => {
136 run_install_script()?;
137 }
138 }
139
140 println!("Update done.");
141 Ok(())
142}
143
144pub fn uninstall() -> Result<()> {
145 if !command_exists("carch") {
146 println!("Carch is not installed.");
147 return Ok(());
148 }
149
150 info!("Starting uninstall...");
151
152 match get_install_method_for_uninstall()? {
153 InstallMethod::Cargo | InstallMethod::CargoBinstall => {
154 run_command(Command::new("cargo").arg("uninstall").arg("carch-cli"))?;
155 }
156 InstallMethod::InstallScript => {
157 println!("Removing carch...");
158
159 let is_termux = std::env::var("TERMUX_VERSION").is_ok()
160 || Path::new("/data/data/com.termux").exists();
161
162 let binary_paths = if is_termux {
163 let prefix =
164 std::env::var("PREFIX").unwrap_or("/data/data/com.termux/files/usr".into());
165 vec![
166 format!("{prefix}/bin/carch"),
167 format!("{prefix}/share/bash-completion/completions/carch"),
168 format!("{prefix}/share/zsh/site-functions/_carch"),
169 format!("{prefix}/share/fish/vendor_completions.d/carch.fish"),
170 format!("{prefix}/share/man/man1/carch.1"),
171 ]
172 } else {
173 vec![
174 "/usr/local/bin/carch".into(),
175 "/usr/share/bash-completion/completions/carch".into(),
176 "/usr/share/zsh/site-functions/_carch".into(),
177 "/usr/share/fish/vendor_completions.d/carch.fish".into(),
178 "/usr/share/man/man1/carch.1".into(),
179 "/usr/share/applications/carch.desktop".into(),
180 ]
181 };
182
183 for path in &binary_paths {
184 if Path::new(path).exists() {
185 if is_termux {
186 run_command(Command::new("rm").arg("-f").arg(path))?;
187 } else {
188 run_command(Command::new("sudo").arg("rm").arg("-f").arg(path))?;
189 }
190 println!(" Removed {path}");
191 }
192 }
193
194 if let Ok(home) = std::env::var("HOME") {
195 let config_dir = Path::new(&home).join(".config/carch");
196 if config_dir.exists() {
197 fs::remove_dir_all(&config_dir)?;
198 println!(" Removed {config_dir:?}");
199 }
200 }
201
202 println!("carch has been removed.");
203 }
204 }
205
206 println!("Uninstallation done.");
207 Ok(())
208}