reminder_cli/
daemon.rs

1use crate::notification::send_notification;
2use crate::storage::Storage;
3use crate::{log_debug, log_error, log_info};
4use anyhow::{Context, Result};
5use chrono::Local;
6use std::fs;
7use std::process::{Command, Stdio};
8use std::thread;
9use std::time::Duration;
10
11const POLL_INTERVAL_SECS: u64 = 10;
12const HEARTBEAT_INTERVAL_SECS: u64 = 30;
13const HEARTBEAT_TIMEOUT_SECS: u64 = 120;
14
15pub fn start_daemon() -> Result<()> {
16    let pid_file = Storage::pid_file_path()?;
17
18    if is_daemon_running()? {
19        println!("Daemon is already running");
20        return Ok(());
21    }
22
23    let exe = std::env::current_exe()?;
24
25    let child = Command::new(exe)
26        .arg("daemon")
27        .arg("run")
28        .stdin(Stdio::null())
29        .stdout(Stdio::null())
30        .stderr(Stdio::null())
31        .spawn()
32        .context("Failed to start daemon process")?;
33
34    fs::write(&pid_file, child.id().to_string())?;
35    println!("Daemon started with PID: {}", child.id());
36
37    Ok(())
38}
39
40pub fn stop_daemon() -> Result<()> {
41    let pid_file = Storage::pid_file_path()?;
42
43    if !pid_file.exists() {
44        println!("Daemon is not running");
45        return Ok(());
46    }
47
48    let pid_str = fs::read_to_string(&pid_file)?;
49    let pid: i32 = pid_str.trim().parse()?;
50
51    #[cfg(unix)]
52    {
53        let _ = Command::new("kill").arg(pid.to_string()).status();
54    }
55
56    #[cfg(windows)]
57    {
58        let _ = Command::new("taskkill")
59            .args(["/PID", &pid.to_string(), "/F"])
60            .status();
61    }
62
63    fs::remove_file(&pid_file)?;
64    println!("Daemon stopped");
65
66    Ok(())
67}
68
69pub fn daemon_status() -> Result<()> {
70    let running = is_daemon_running()?;
71    let healthy = is_daemon_healthy()?;
72
73    if running {
74        let pid_file = Storage::pid_file_path()?;
75        let pid = fs::read_to_string(&pid_file)?;
76        println!("Daemon is running (PID: {})", pid.trim());
77
78        if healthy {
79            println!("Health: OK (heartbeat active)");
80        } else {
81            println!("Health: WARNING (heartbeat stale - daemon may be stuck)");
82        }
83
84        // Show last heartbeat time
85        if let Ok(heartbeat_path) = Storage::heartbeat_file_path() {
86            if heartbeat_path.exists() {
87                if let Ok(content) = fs::read_to_string(&heartbeat_path) {
88                    if let Ok(timestamp) = content.trim().parse::<i64>() {
89                        let dt = chrono::DateTime::from_timestamp(timestamp, 0)
90                            .map(|t| t.with_timezone(&Local));
91                        if let Some(dt) = dt {
92                            println!(
93                                "Last heartbeat: {}",
94                                dt.format("%Y-%m-%d %H:%M:%S")
95                            );
96                        }
97                    }
98                }
99            }
100        }
101    } else {
102        println!("Daemon is not running");
103    }
104    Ok(())
105}
106
107pub fn is_daemon_running() -> Result<bool> {
108    let pid_file = Storage::pid_file_path()?;
109
110    if !pid_file.exists() {
111        return Ok(false);
112    }
113
114    let pid_str = fs::read_to_string(&pid_file)?;
115    let pid: u32 = match pid_str.trim().parse() {
116        Ok(p) => p,
117        Err(_) => {
118            fs::remove_file(&pid_file)?;
119            return Ok(false);
120        }
121    };
122
123    #[cfg(unix)]
124    {
125        let output = Command::new("kill")
126            .args(["-0", &pid.to_string()])
127            .output();
128
129        match output {
130            Ok(o) => Ok(o.status.success()),
131            Err(_) => {
132                fs::remove_file(&pid_file)?;
133                Ok(false)
134            }
135        }
136    }
137
138    #[cfg(windows)]
139    {
140        let output = Command::new("tasklist")
141            .args(["/FI", &format!("PID eq {}", pid)])
142            .output();
143
144        match output {
145            Ok(o) => {
146                let stdout = String::from_utf8_lossy(&o.stdout);
147                Ok(stdout.contains(&pid.to_string()))
148            }
149            Err(_) => {
150                fs::remove_file(&pid_file)?;
151                Ok(false)
152            }
153        }
154    }
155}
156
157
158
159fn write_heartbeat() {
160    if let Ok(heartbeat_path) = Storage::heartbeat_file_path() {
161        let timestamp = Local::now().timestamp().to_string();
162        let _ = fs::write(heartbeat_path, timestamp);
163    }
164}
165
166fn check_heartbeat() -> Result<bool> {
167    let heartbeat_path = Storage::heartbeat_file_path()?;
168
169    if !heartbeat_path.exists() {
170        return Ok(false);
171    }
172
173    let content = fs::read_to_string(&heartbeat_path)?;
174    let timestamp: i64 = content.trim().parse().unwrap_or(0);
175    let now = Local::now().timestamp();
176
177    Ok((now - timestamp) < HEARTBEAT_TIMEOUT_SECS as i64)
178}
179
180pub fn is_daemon_healthy() -> Result<bool> {
181    if !is_daemon_running()? {
182        return Ok(false);
183    }
184    check_heartbeat()
185}
186
187pub fn run_daemon_loop() -> Result<()> {
188    let storage = Storage::new()?;
189    log_info!("Daemon started");
190    write_heartbeat();
191
192    let mut heartbeat_counter = 0u64;
193
194    loop {
195        match storage.load() {
196            Ok(mut reminders) => {
197                let mut updated = false;
198
199                for reminder in reminders.iter_mut() {
200                    if reminder.is_due() {
201                        log_info!("Triggering reminder: {}", reminder.title);
202
203                        if let Err(e) = send_notification(reminder) {
204                            log_error!("Failed to send notification: {}", e);
205                        }
206                        reminder.calculate_next_trigger();
207                        updated = true;
208                    }
209                }
210
211                if updated {
212                    if let Err(e) = storage.save(&reminders) {
213                        log_error!("Failed to save reminders: {}", e);
214                    }
215                }
216            }
217            Err(e) => {
218                log_error!("Failed to load reminders: {}", e);
219            }
220        }
221
222        // Write heartbeat periodically
223        heartbeat_counter += POLL_INTERVAL_SECS;
224        if heartbeat_counter >= HEARTBEAT_INTERVAL_SECS {
225            write_heartbeat();
226            log_debug!("Heartbeat written");
227            heartbeat_counter = 0;
228        }
229
230        thread::sleep(Duration::from_secs(POLL_INTERVAL_SECS));
231    }
232}
233
234/// Generate launchd plist for macOS auto-start
235#[cfg(target_os = "macos")]
236pub fn generate_launchd_plist() -> Result<String> {
237    let exe = std::env::current_exe()?;
238    let plist = format!(
239        r#"<?xml version="1.0" encoding="UTF-8"?>
240<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
241<plist version="1.0">
242<dict>
243    <key>Label</key>
244    <string>com.reminder-cli.daemon</string>
245    <key>ProgramArguments</key>
246    <array>
247        <string>{}</string>
248        <string>daemon</string>
249        <string>run</string>
250    </array>
251    <key>RunAtLoad</key>
252    <true/>
253    <key>KeepAlive</key>
254    <true/>
255</dict>
256</plist>"#,
257        exe.display()
258    );
259    Ok(plist)
260}
261
262/// Generate systemd service for Linux auto-start
263#[cfg(target_os = "linux")]
264pub fn generate_systemd_service() -> Result<String> {
265    let exe = std::env::current_exe()?;
266    let service = format!(
267        r#"[Unit]
268Description=Reminder CLI Daemon
269After=network.target
270
271[Service]
272Type=simple
273ExecStart={} daemon run
274Restart=always
275RestartSec=10
276
277[Install]
278WantedBy=default.target"#,
279        exe.display()
280    );
281    Ok(service)
282}
283
284pub fn install_autostart() -> Result<()> {
285    #[cfg(target_os = "macos")]
286    {
287        let plist = generate_launchd_plist()?;
288        let plist_path = dirs::home_dir()
289            .context("Failed to get home directory")?
290            .join("Library/LaunchAgents/com.reminder-cli.daemon.plist");
291
292        fs::write(&plist_path, plist)?;
293        println!("Created launchd plist at: {}", plist_path.display());
294        println!("To enable: launchctl load {}", plist_path.display());
295    }
296
297    #[cfg(target_os = "linux")]
298    {
299        let service = generate_systemd_service()?;
300        let service_path = dirs::home_dir()
301            .context("Failed to get home directory")?
302            .join(".config/systemd/user/reminder-cli.service");
303
304        if let Some(parent) = service_path.parent() {
305            fs::create_dir_all(parent)?;
306        }
307
308        fs::write(&service_path, service)?;
309        println!("Created systemd service at: {}", service_path.display());
310        println!("To enable: systemctl --user enable --now reminder-cli");
311    }
312
313    #[cfg(target_os = "windows")]
314    {
315        println!("Windows auto-start: Add a shortcut to 'reminder daemon start' in your Startup folder");
316        println!(
317            "Startup folder: {}",
318            dirs::data_local_dir()
319                .map(|p| p
320                    .parent()
321                    .unwrap_or(&p)
322                    .join("Roaming/Microsoft/Windows/Start Menu/Programs/Startup")
323                    .display()
324                    .to_string())
325                .unwrap_or_else(|| "Unknown".to_string())
326        );
327    }
328
329    Ok(())
330}