1use crate::commands;
2use crate::state::{clear_favorite_theme, load_favorite_theme, save_favorite_theme};
3use carch_core::error::{CarchError, Result};
4use carch_core::{VALID_THEMES, is_valid_theme, version};
5use clap::builder::styling::{AnsiColor, Style};
6use clap::{ArgAction, CommandFactory, Parser, Subcommand};
7use env_logger::{Builder, Target};
8use log::info;
9use std::env;
10use std::fs::{self, OpenOptions};
11use std::path::PathBuf;
12use std::time::{SystemTime, UNIX_EPOCH};
13
14fn timestamped_log_filename() -> String {
15 let secs = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
16
17 let days = (secs / 86400) as i64 + 719468;
18 let era = days.div_euclid(146097);
19 let doe = (days - era * 146097) as u64;
20 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
21 let year_era = yoe as i64 + era * 400;
22 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
23 let mp = (5 * doy + 2) / 153;
24 let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
25 let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
26 let year = (year_era + if month <= 2 { 1 } else { 0 }) as u32;
27
28 let tod = secs % 86400;
29 let hour = (tod / 3600) as u32;
30 let minute = ((tod % 3600) / 60) as u32;
31 let second = (tod % 60) as u32;
32
33 format!("carch-{year:04}{month:02}{day:02}-{hour:02}{minute:02}{second:02}.log")
34}
35
36const MAX_LOG_FILES: usize = 5;
37
38fn rotate_logs(log_dir: &std::path::Path) {
39 let mut logs: Vec<PathBuf> = fs::read_dir(log_dir)
40 .into_iter()
41 .flatten()
42 .filter_map(|e| e.ok())
43 .map(|e| e.path())
44 .filter(|p| p.extension().is_some_and(|ext| ext == "log"))
45 .collect();
46
47 logs.sort();
48
49 if logs.len() > MAX_LOG_FILES {
50 for old in &logs[..logs.len() - MAX_LOG_FILES] {
51 let _ = fs::remove_file(old);
52 }
53 }
54}
55
56fn styles() -> clap::builder::Styles {
57 clap::builder::Styles::styled()
58 .header(Style::new().fg_color(Some(AnsiColor::Green.into())).bold())
59 .usage(Style::new().fg_color(Some(AnsiColor::Green.into())).bold())
60 .literal(Style::new().fg_color(Some(AnsiColor::Cyan.into())))
61 .placeholder(Style::new().fg_color(Some(AnsiColor::Cyan.into())))
62}
63
64#[derive(Parser)]
65#[command(
66 author,
67 about = "A CLI tool to automate Linux system setup",
68 long_about = "A Rust-based CLI tool to streamline and automate your Linux system's initial setup.\nIt offers automated scripts that save users time setting up their Linux environment.",
69 styles = styles()
70)]
71pub struct Cli {
72 #[command(subcommand)]
73 pub command: Option<Commands>,
74 #[arg(short = 'v', long = "version", action = ArgAction::SetTrue, help = "Print version information")]
75 version: bool,
76 #[arg(short = 'c', long, global = true, help = "Set theme to Catppuccin Mocha")]
77 pub catppuccin_mocha: bool,
78 #[arg(short = 'd', long, global = true, help = "Set theme to Dracula")]
79 pub dracula: bool,
80 #[arg(short = 'g', long, global = true, help = "Set theme to Gruvbox")]
81 pub gruvbox: bool,
82 #[arg(short = 'n', long, global = true, help = "Set theme to Nord")]
83 pub nord: bool,
84 #[arg(short = 'r', long, global = true, help = "Set theme to Rosé Pine")]
85 pub rose_pine: bool,
86 #[arg(long, global = true, value_name = "THEME")]
88 pub fav: Option<String>,
89 #[arg(long, global = true, conflicts_with = "fav")]
91 pub unfav: bool,
92}
93
94#[derive(Subcommand)]
95pub enum Commands {
96 #[command(about = "Check for updates")]
97 CheckUpdate,
98 #[command(about = "Update the application")]
99 Update,
100 #[command(about = "Uninstall the application")]
101 Uninstall,
102 #[command(about = "Generate shell completions (bash, zsh, fish)")]
103 Completions {
104 #[arg(value_enum, help = "Shell to generate completions for")]
105 shell: clap_complete::Shell,
106 },
107}
108
109#[derive(Clone, Default)]
110pub struct Settings {
111 pub log_mode: bool,
112 pub theme: String,
113 pub theme_locked: bool,
114}
115
116pub fn parse_args() -> Result<()> {
117 let cli = Cli::parse();
118
119 if cli.version {
120 println!("{}", version::get_current_version());
121 return Ok(());
122 }
123
124 if let Some(theme) = cli.fav.as_deref() {
125 if !is_valid_theme(theme) {
126 return Err(CarchError::Command(format!(
127 "Unknown theme '{theme}'. Valid themes: {}",
128 VALID_THEMES.join(", ")
129 )));
130 }
131 return save_favorite_theme(theme).map(|()| {
132 println!("Favorite theme set to '{theme}'. It will be used on future launches.");
133 });
134 }
135 if cli.unfav {
136 match clear_favorite_theme() {
137 Ok(true) => println!("Favorite theme cleared."),
138 Ok(false) => println!("No favorite theme was set."),
139 Err(e) => return Err(e),
140 }
141 return Ok(());
142 }
143
144 let mut settings = Settings { log_mode: true, ..Default::default() };
145
146 let explicit_theme =
147 cli.catppuccin_mocha || cli.dracula || cli.gruvbox || cli.nord || cli.rose_pine;
148
149 settings.theme = if cli.catppuccin_mocha {
150 "catppuccin-mocha".to_string()
151 } else if cli.dracula {
152 "dracula".to_string()
153 } else if cli.gruvbox {
154 "gruvbox".to_string()
155 } else if cli.nord {
156 "nord".to_string()
157 } else if cli.rose_pine {
158 "rose-pine".to_string()
159 } else if let Some(fav) = load_favorite_theme() {
160 settings.theme_locked = true;
162 fav
163 } else {
164 "catppuccin-mocha".to_string()
165 };
166
167 if explicit_theme {
168 settings.theme_locked = true;
169 }
170
171 match cli.command {
172 Some(Commands::CheckUpdate) => {
173 info!("Checking for updates");
174 commands::check_for_updates()
175 }
176 Some(Commands::Update) => {
177 info!("Running update process");
178 commands::update()
179 }
180 Some(Commands::Uninstall) => {
181 info!("Running uninstall process");
182 commands::uninstall()
183 }
184 Some(Commands::Completions { shell }) => {
185 let mut cmd = Cli::command();
186 clap_complete::generate(shell, &mut cmd, "carch", &mut std::io::stdout());
187 Ok(())
188 }
189 None => {
190 let home_dir = env::var("HOME").map_err(|_| CarchError::HomeDirNotFound)?;
191 let log_dir = PathBuf::from(home_dir).join(".config/carch");
192 fs::create_dir_all(&log_dir)?;
193 let log_file = log_dir.join(timestamped_log_filename());
194
195 let file =
196 OpenOptions::new().create(true).write(true).truncate(true).open(&log_file)?;
197
198 Builder::new()
199 .target(Target::Pipe(Box::new(file)))
200 .filter(None, log::LevelFilter::Info)
201 .init();
202 info!("Carch TUI started");
203
204 rotate_logs(&log_dir);
205
206 let result = crate::run_tui(settings);
207
208 println!("Log saved: {}", log_file.display());
209
210 result
211 }
212 }
213}