Skip to main content

carch_cli/
setup.rs

1use crate::args::Cli;
2use carch_core::error::{CarchError, Result};
3use clap::CommandFactory;
4use std::fs;
5use std::path::PathBuf;
6
7#[cfg(target_os = "linux")]
8const DESKTOP_FILE: &str = "[Desktop Entry]
9Name=Carch
10Comment=A Rust-powered TUI that automates post-installation setup and theming on Arch, Fedora, and openSUSE
11Exec=carch
12Icon=utilities-terminal
13Type=Application
14Terminal=true
15Categories=Utility;
16Keywords=linux;setup;script;configuration;automate;system;
17";
18
19fn is_termux() -> bool {
20    std::env::var("TERMUX_VERSION").is_ok() || std::env::var("PREFIX").is_ok()
21}
22
23fn is_root() -> bool {
24    std::env::var("EUID").is_ok_and(|v| v == "0")
25}
26
27fn termux_prefix() -> PathBuf {
28    std::env::var("PREFIX")
29        .map(PathBuf::from)
30        .unwrap_or_else(|_| PathBuf::from("/data/data/com.termux/files/usr"))
31}
32
33fn bash_completion_dir() -> PathBuf {
34    if is_termux() {
35        termux_prefix().join("share/bash-completion/completions")
36    } else if is_root() {
37        PathBuf::from("/usr/share/bash-completion/completions")
38    } else {
39        dirs::data_dir()
40            .unwrap_or_else(|| PathBuf::from("~/.local/share"))
41            .join("bash-completion/completions")
42    }
43}
44
45fn zsh_completion_dir() -> PathBuf {
46    if is_termux() {
47        termux_prefix().join("share/zsh/site-functions")
48    } else if is_root() {
49        PathBuf::from("/usr/share/zsh/site-functions")
50    } else {
51        dirs::data_dir()
52            .unwrap_or_else(|| PathBuf::from("~/.local/share"))
53            .join("zsh/site-functions")
54    }
55}
56
57fn fish_completion_dir() -> PathBuf {
58    if is_termux() {
59        termux_prefix().join("share/fish/vendor_completions.d")
60    } else if is_root() {
61        PathBuf::from("/usr/share/fish/vendor_completions.d")
62    } else {
63        dirs::data_dir()
64            .unwrap_or_else(|| PathBuf::from("~/.local/share"))
65            .join("fish/vendor_completions.d")
66    }
67}
68
69fn man_dir() -> PathBuf {
70    if is_termux() {
71        termux_prefix().join("share/man/man1")
72    } else if is_root() {
73        PathBuf::from("/usr/share/man/man1")
74    } else {
75        dirs::data_dir().unwrap_or_else(|| PathBuf::from("~/.local/share")).join("man/man1")
76    }
77}
78
79fn write_file(path: &PathBuf, content: &[u8], dry_run: bool) -> Result<()> {
80    if dry_run {
81        return Ok(());
82    }
83    if let Some(parent) = path.parent() {
84        fs::create_dir_all(parent)?;
85    }
86    fs::write(path, content)?;
87    Ok(())
88}
89
90pub fn run_setup(dry_run: bool) -> Result<()> {
91    let mut cmd = Cli::command();
92    cmd = cmd.name("carch");
93    cmd = cmd.long_about(
94        "A Rust-powered TUI that automates post-installation setup and theming on Arch, Fedora, and openSUSE\nIt offers modular scripts that save you time setting up your Linux environment.",
95    );
96
97    if dry_run {
98        println!("(dry run) Would install:");
99    }
100
101    let mut installed = Vec::new();
102
103    let bash_path = bash_completion_dir().join("carch");
104    let mut bash_content = Vec::new();
105    clap_complete::generate(
106        clap_complete::Shell::Bash,
107        &mut cmd.clone(),
108        "carch",
109        &mut bash_content,
110    );
111    write_file(&bash_path, &bash_content, dry_run)?;
112    installed.push(format!("bash completions → {}", bash_path.display()));
113
114    let zsh_path = zsh_completion_dir().join("_carch");
115    let mut zsh_content = Vec::new();
116    clap_complete::generate(clap_complete::Shell::Zsh, &mut cmd.clone(), "carch", &mut zsh_content);
117    write_file(&zsh_path, &zsh_content, dry_run)?;
118    installed.push(format!("zsh completions → {}", zsh_path.display()));
119
120    let fish_path = fish_completion_dir().join("carch.fish");
121    let mut fish_content = Vec::new();
122    clap_complete::generate(
123        clap_complete::Shell::Fish,
124        &mut cmd.clone(),
125        "carch",
126        &mut fish_content,
127    );
128    write_file(&fish_path, &fish_content, dry_run)?;
129    installed.push(format!("fish completions → {}", fish_path.display()));
130
131    let date = std::process::Command::new("date")
132        .arg("+%B %d, %Y")
133        .output()
134        .ok()
135        .and_then(|o| String::from_utf8(o.stdout).ok())
136        .unwrap_or_else(|| "unknown".to_string());
137
138    let man = clap_mangen::Man::new(cmd.clone())
139        .title("carch")
140        .section("1")
141        .date(date.trim())
142        .source("Carch")
143        .manual("Carch");
144
145    let mut buf = Vec::new();
146    man.render(&mut buf)?;
147
148    let mut content = String::from_utf8(buf)
149        .map_err(|e| CarchError::Command(format!("man page UTF-8 error: {e}")))?;
150    for sub in cmd.get_subcommands() {
151        let name = sub.get_name();
152        let escaped = name.replace('-', "\\-");
153        let old = format!("carch\\-{escaped}(1)");
154        let new = format!("\\fB{name}\\fR");
155        content = content.replace(&old, &new);
156    }
157    content = content.replace("carch\\-help(1)", "\\fBhelp\\fR");
158
159    content.push_str(
160        r#".SH DOCUMENTATION
161Documentation and source code available at:
162.br
163https://github.com/harilvfs/carch
164
165.SH AUTHOR
166Hari Chalise <harilvfs@chalisehari.com.np>
167
168.SH REPORTING BUGS
169If you encounter bugs or issues, please report them at:
170.br
171https://github.com/harilvfs/carch/issues
172"#,
173    );
174
175    let man_path = man_dir().join("carch.1");
176    write_file(&man_path, content.as_bytes(), dry_run)?;
177    installed.push(format!("man page → {}", man_path.display()));
178
179    #[cfg(target_os = "linux")]
180    if !is_termux() {
181        let desktop_dir = if is_root() {
182            PathBuf::from("/usr/share/applications")
183        } else {
184            dirs::data_dir().unwrap_or_else(|| PathBuf::from("~/.local/share")).join("applications")
185        };
186        let desktop_path = desktop_dir.join("carch.desktop");
187        write_file(&desktop_path, DESKTOP_FILE.as_bytes(), dry_run)?;
188        installed.push(format!("desktop file → {}", desktop_path.display()));
189    }
190
191    for msg in &installed {
192        if dry_run {
193            println!("  {msg}");
194        } else {
195            println!("✓ {msg}");
196        }
197    }
198
199    Ok(())
200}