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