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 styles = styles()
69)]
70pub struct Cli {
71 #[command(subcommand)]
72 pub command: Option<Commands>,
73 #[arg(short = 'v', long = "version", action = ArgAction::SetTrue, help = "Print version information")]
74 version: bool,
75 #[arg(
76 long,
77 global = true,
78 value_name = "THEME",
79 help = "Set and persist theme (catppuccin-mocha, dracula, gruvbox, nord, rose-pine, or default to reset)"
80 )]
81 pub set_theme: Option<String>,
82}
83
84#[derive(Subcommand)]
85pub enum Commands {
86 #[command(about = "Check for updates")]
87 CheckUpdate,
88 #[command(about = "Update the application")]
89 Update,
90 #[command(about = "Uninstall the application")]
91 Uninstall,
92 #[command(about = "Generate shell completions (bash, zsh, fish)")]
93 Completions {
94 #[arg(value_enum, help = "Shell to generate completions for")]
95 shell: clap_complete::Shell,
96 },
97}
98
99#[derive(Clone, Default)]
100pub struct Settings {
101 pub log_mode: bool,
102 pub theme: String,
103 pub theme_locked: bool,
104 pub log_path: Option<String>,
105}
106
107pub fn parse_args() -> Result<()> {
108 let cli = Cli::parse();
109
110 if cli.version {
111 println!("{}", version::get_current_version());
112 return Ok(());
113 }
114
115 let mut settings = Settings { log_mode: true, ..Default::default() };
116
117 if let Some(theme) = &cli.set_theme {
118 if theme == "default" {
119 let _ = clear_favorite_theme();
120 println!("Default theme restored.");
121 } else if is_valid_theme(theme) {
122 save_favorite_theme(theme)?;
123 println!("{theme} has been set as your default theme.");
124 } else {
125 return Err(CarchError::Command(format!(
126 "Unknown theme '{theme}'. Valid themes: {}",
127 VALID_THEMES.join(", ")
128 )));
129 }
130 return Ok(());
131 } else if let Some(fav) = load_favorite_theme() {
132 settings.theme = fav;
133 settings.theme_locked = true;
134 } else {
135 settings.theme = "catppuccin-mocha".to_string();
136 }
137
138 match cli.command {
139 Some(Commands::CheckUpdate) => {
140 info!("Checking for updates");
141 commands::check_for_updates()
142 }
143 Some(Commands::Update) => {
144 info!("Running update process");
145 commands::update()
146 }
147 Some(Commands::Uninstall) => {
148 info!("Running uninstall process");
149 commands::uninstall()
150 }
151 Some(Commands::Completions { shell }) => {
152 let mut cmd = Cli::command();
153 clap_complete::generate(shell, &mut cmd, "carch", &mut std::io::stdout());
154 Ok(())
155 }
156 None => {
157 let home_dir = env::var("HOME").map_err(|_| CarchError::HomeDirNotFound)?;
158 let log_dir = PathBuf::from(home_dir).join(".config/carch");
159 fs::create_dir_all(&log_dir)?;
160 let log_file = log_dir.join(timestamped_log_filename());
161
162 let file =
163 OpenOptions::new().create(true).write(true).truncate(true).open(&log_file)?;
164
165 Builder::new()
166 .target(Target::Pipe(Box::new(file)))
167 .filter(None, log::LevelFilter::Info)
168 .init();
169 info!("Carch TUI started");
170
171 rotate_logs(&log_dir);
172
173 settings.log_path = Some(log_file.display().to_string());
174 let result = crate::run_tui(settings);
175
176 let has_issues = fs::read_to_string(&log_file)
177 .map(|content| {
178 content.lines().any(|line| {
179 line.contains("error") || line.contains("failed") || line.contains("Failed")
180 })
181 })
182 .unwrap_or(false);
183
184 if has_issues || result.is_err() {
185 println!("Log saved: {}", log_file.display());
186 }
187
188 result
189 }
190 }
191}