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 InstallScript,
91}
92
93fn get_install_method() -> Result<InstallMethod> {
94 print!("Installed via (c)argo or (i)nstall script? ");
95 io::stdout().flush()?;
96 let mut choice = String::new();
97 io::stdin().read_line(&mut choice)?;
98 match choice.trim().to_lowercase().as_str() {
99 "c" | "cargo" => Ok(InstallMethod::Cargo),
100 "i" | "install script" => Ok(InstallMethod::InstallScript),
101 _ => Err(CarchError::Command("Invalid choice. Please run the command again.".into())),
102 }
103}
104
105pub fn update() -> Result<()> {
106 if !command_exists("carch") {
107 println!("Carch is not installed. Please install it first.");
108 return Ok(());
109 }
110
111 info!("Starting update...");
112 println!("Updating carch...");
113
114 match get_install_method()? {
115 InstallMethod::Cargo => {
116 run_command(Command::new("cargo").arg("install").arg("carch-cli").arg("--force"))?;
117 }
118 InstallMethod::InstallScript => {
119 run_install_script()?;
120 }
121 }
122
123 println!("Update done.");
124 Ok(())
125}
126
127pub fn uninstall() -> Result<()> {
128 if !command_exists("carch") {
129 println!("Carch is not installed.");
130 return Ok(());
131 }
132
133 info!("Starting uninstall...");
134
135 match get_install_method()? {
136 InstallMethod::Cargo => {
137 run_command(Command::new("cargo").arg("uninstall").arg("carch-cli"))?;
138 }
139 InstallMethod::InstallScript => {
140 println!("Removing carch...");
141
142 let is_termux = std::env::var("TERMUX_VERSION").is_ok()
143 || Path::new("/data/data/com.termux").exists();
144
145 let binary_paths = if is_termux {
146 let prefix =
147 std::env::var("PREFIX").unwrap_or("/data/data/com.termux/files/usr".into());
148 vec![
149 format!("{prefix}/bin/carch"),
150 format!("{prefix}/share/bash-completion/completions/carch"),
151 format!("{prefix}/share/zsh/site-functions/_carch"),
152 format!("{prefix}/share/fish/vendor_completions.d/carch.fish"),
153 format!("{prefix}/share/man/man1/carch.1"),
154 ]
155 } else {
156 vec![
157 "/usr/local/bin/carch".into(),
158 "/usr/share/bash-completion/completions/carch".into(),
159 "/usr/share/zsh/site-functions/_carch".into(),
160 "/usr/share/fish/vendor_completions.d/carch.fish".into(),
161 "/usr/share/man/man1/carch.1".into(),
162 "/usr/share/applications/carch.desktop".into(),
163 ]
164 };
165
166 for path in &binary_paths {
167 if Path::new(path).exists() {
168 if is_termux {
169 run_command(Command::new("rm").arg("-f").arg(path))?;
170 } else {
171 run_command(Command::new("sudo").arg("rm").arg("-f").arg(path))?;
172 }
173 println!(" Removed {path}");
174 }
175 }
176
177 if let Ok(home) = std::env::var("HOME") {
178 let config_dir = Path::new(&home).join(".config/carch");
179 if config_dir.exists() {
180 fs::remove_dir_all(&config_dir)?;
181 println!(" Removed {config_dir:?}");
182 }
183 }
184
185 println!("carch has been removed.");
186 }
187 }
188
189 println!("Uninstallation done.");
190 Ok(())
191}