bkr 1.0.0

Backup and restore tool for syncing files to AWS S3 with native zstd compression
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
use crate::config::ConfigParser;
use crate::constants::{time, windows_tasks};
use crate::error::{BakerError, Result};
use std::fs;
use std::path::PathBuf;
use std::process::Command;

#[derive(Debug, Clone)]
pub struct DaemonStatus {
    pub installed: bool,
    pub backup: bool,
    pub restore: bool,
    pub schedule: Option<String>,
    pub exercise_restore: Option<bool>,
    pub platform: String,
}

pub struct DaemonManager {
    backup_service_name: String,
    restore_service_name: String,
    executable_path: PathBuf,
    config_path: Option<String>,
}

impl DaemonManager {
    pub fn new(config_path: Option<&str>) -> Self {
        // Get the path to the baker executable
        let executable_path = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("baker"));

        Self {
            backup_service_name: "com.baker.backup".to_string(),
            restore_service_name: "com.baker.restore".to_string(),
            executable_path,
            config_path: config_path.map(String::from),
        }
    }

    /// Check if daemon is actually installed
    pub fn is_installed(&self) -> DaemonStatus {
        let platform = std::env::consts::OS.to_string();

        let mut status = DaemonStatus {
            installed: false,
            backup: false,
            restore: false,
            schedule: None,
            exercise_restore: None,
            platform: platform.clone(),
        };

        // Try to read schedule from config
        if let Ok(parser) = ConfigParser::new(self.config_path.as_deref()) {
            if let Some(schedule) = &parser.get_config().daemon_schedule {
                status.schedule = Some(schedule.every.clone());
                status.exercise_restore = Some(schedule.exercise_restore);
            }
        }

        match platform.as_str() {
            "macos" => {
                let plist_dir = dirs::home_dir()
                    .map(|h| h.join("Library/LaunchAgents"))
                    .unwrap_or_default();
                let backup_plist_path = plist_dir.join(format!("{}.plist", self.backup_service_name));
                let restore_plist_path =
                    plist_dir.join(format!("{}.plist", self.restore_service_name));

                status.backup = backup_plist_path.exists();
                status.restore = restore_plist_path.exists();
                status.installed = status.backup || status.restore;
            }
            "linux" => {
                let systemd_dir = dirs::home_dir()
                    .map(|h| h.join(".config/systemd/user"))
                    .unwrap_or_default();
                let backup_service_path = systemd_dir.join("baker-backup.service");
                let backup_timer_path = systemd_dir.join("baker-backup.timer");
                let restore_service_path = systemd_dir.join("baker-restore.service");
                let restore_timer_path = systemd_dir.join("baker-restore.timer");

                status.backup = backup_service_path.exists() && backup_timer_path.exists();
                status.restore = restore_service_path.exists() && restore_timer_path.exists();
                status.installed = status.backup || status.restore;
            }
            "windows" => {
                // Check if Windows scheduled tasks exist
                status.backup = Command::new("schtasks")
                    .args(["/Query", "/TN", windows_tasks::BACKUP])
                    .output()
                    .map(|o| o.status.success())
                    .unwrap_or(false);

                status.restore = Command::new("schtasks")
                    .args(["/Query", "/TN", windows_tasks::RESTORE])
                    .output()
                    .map(|o| o.status.success())
                    .unwrap_or(false);

                status.installed = status.backup || status.restore;
            }
            _ => {}
        }

        status
    }

    pub fn install(&self) -> Result<()> {
        let platform = std::env::consts::OS;

        println!("Installing baker daemon for {}...", platform);

        // Validate config
        let parser = ConfigParser::new(self.config_path.as_deref())?;
        let config = parser.get_config();

        let schedule = config.daemon_schedule.as_ref().ok_or_else(|| {
            BakerError::Daemon("daemon_schedule is not configured in config file".to_string())
        })?;

        println!("   Schedule: {}", schedule.every);
        if schedule.exercise_restore {
            println!("   Exercise restore: enabled");
        }

        match platform {
            "macos" => self.install_macos(schedule)?,
            "linux" => self.install_linux(schedule)?,
            "windows" => self.install_windows(schedule)?,
            _ => return Err(BakerError::UnsupportedPlatform(platform.to_string())),
        }

        println!("\nDaemon installed successfully!");
        println!("\nTo check status: baker daemon-status");

        Ok(())
    }

    pub fn uninstall(&self) -> Result<()> {
        let platform = std::env::consts::OS;

        println!("Uninstalling baker daemon for {}...", platform);

        match platform {
            "macos" => self.uninstall_macos()?,
            "linux" => self.uninstall_linux()?,
            "windows" => self.uninstall_windows()?,
            _ => return Err(BakerError::UnsupportedPlatform(platform.to_string())),
        }

        println!("\nDaemon uninstalled successfully!");

        Ok(())
    }

    pub fn status(&self) -> Result<()> {
        let platform = std::env::consts::OS;

        println!("Checking daemon status for {}...\n", platform);

        match platform {
            "macos" => self.status_macos()?,
            "linux" => self.status_linux()?,
            "windows" => self.status_windows()?,
            _ => return Err(BakerError::UnsupportedPlatform(platform.to_string())),
        }

        Ok(())
    }

    fn parse_interval(&self, interval: &str) -> Result<u64> {
        let re = regex::Regex::new(r"^(\d+)(s|m|h|d)$").unwrap();
        let caps = re
            .captures(interval)
            .ok_or_else(|| BakerError::InvalidInterval(interval.to_string()))?;

        let value: u64 = caps[1].parse().map_err(|_| {
            BakerError::InvalidInterval(interval.to_string())
        })?;
        let unit = &caps[2];

        // Return seconds
        Ok(match unit {
            "s" => value,
            "m" => value * time::SECONDS_PER_MINUTE,
            "h" => value * time::SECONDS_PER_HOUR,
            "d" => value * time::SECONDS_PER_DAY,
            _ => return Err(BakerError::InvalidInterval(interval.to_string())),
        })
    }

    // ============================================================================
    // Shared Generators
    // ============================================================================

    fn generate_macos_plist(
        &self,
        command: &str,
        service_name: &str,
        interval_seconds: u64,
    ) -> String {
        let logs_dir = dirs::home_dir()
            .map(|h| h.join("Library/Logs"))
            .unwrap_or_default();

        let mut program_args = vec![
            format!("        <string>{}</string>", self.executable_path.display()),
            format!("        <string>{}</string>", command),
        ];

        if let Some(config_path) = &self.config_path {
            program_args.push("        <string>--config</string>".to_string());
            program_args.push(format!("        <string>{}</string>", config_path));
        }

        format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>{}</string>
    <key>ProgramArguments</key>
    <array>
{}
    </array>
    <key>StartInterval</key>
    <integer>{}</integer>
    <key>RunAtLoad</key>
    <true/>
    <key>StandardOutPath</key>
    <string>{}</string>
    <key>StandardErrorPath</key>
    <string>{}</string>
</dict>
</plist>"#,
            service_name,
            program_args.join("\n"),
            interval_seconds,
            logs_dir.join(format!("baker-{}.log", command)).display(),
            logs_dir.join(format!("baker-{}.error.log", command)).display()
        )
    }

    fn generate_systemd_service(&self, command: &str) -> String {
        let config_arg = self
            .config_path
            .as_ref()
            .map(|p| format!("--config \"{}\"", p))
            .unwrap_or_default();

        let label = command.chars().next().unwrap().to_uppercase().to_string()
            + &command[1..];

        format!(
            r#"[Unit]
Description=Baker {} Service
After=network.target

[Service]
Type=oneshot
ExecStart={} {} {}

[Install]
WantedBy=default.target"#,
            label,
            self.executable_path.display(),
            command,
            config_arg
        )
    }

    fn generate_systemd_timer(&self, command: &str, interval: &str) -> String {
        let label = command.chars().next().unwrap().to_uppercase().to_string()
            + &command[1..];

        format!(
            r#"[Unit]
Description=Baker {} Timer
Requires=baker-{}.service

[Timer]
OnBootSec=5min
OnUnitActiveSec={}
Persistent=true

[Install]
WantedBy=timers.target"#,
            label, command, interval
        )
    }

    // ============================================================================
    // macOS (launchd) Implementation
    // ============================================================================

    fn install_macos(&self, schedule: &crate::config::DaemonSchedule) -> Result<()> {
        let plist_dir = dirs::home_dir()
            .map(|h| h.join("Library/LaunchAgents"))
            .ok_or_else(|| BakerError::Daemon("Cannot find home directory".to_string()))?;

        let plist_path = plist_dir.join(format!("{}.plist", self.backup_service_name));
        let logs_dir = dirs::home_dir()
            .map(|h| h.join("Library/Logs"))
            .unwrap_or_default();

        // Ensure directories exist
        fs::create_dir_all(&plist_dir)?;
        fs::create_dir_all(&logs_dir)?;

        let interval_seconds = self.parse_interval(&schedule.every)?;
        let plist_content =
            self.generate_macos_plist("backup", &self.backup_service_name, interval_seconds);

        fs::write(&plist_path, plist_content)?;
        println!("   Created backup plist: {}", plist_path.display());
        println!("   Logs: {}", logs_dir.join("baker-backup.log").display());

        // Install restore task if enabled
        if schedule.exercise_restore {
            self.install_macos_restore(schedule)?;
        }

        // Load the agent
        let load_result = Command::new("launchctl")
            .args(["load", plist_path.to_str().unwrap_or("")])
            .output();

        if load_result.map(|o| o.status.success()).unwrap_or(false) {
            println!("   Loaded backup agent");
        } else {
            println!("   Warning: Failed to load backup agent. You may need to load it manually:");
            println!("   launchctl load {}", plist_path.display());
        }

        Ok(())
    }

    fn install_macos_restore(&self, schedule: &crate::config::DaemonSchedule) -> Result<()> {
        let plist_dir = dirs::home_dir()
            .map(|h| h.join("Library/LaunchAgents"))
            .ok_or_else(|| BakerError::Daemon("Cannot find home directory".to_string()))?;

        let plist_path = plist_dir.join(format!("{}.plist", self.restore_service_name));

        let interval_seconds = self.parse_interval(&schedule.every)?;
        let plist_content =
            self.generate_macos_plist("restore", &self.restore_service_name, interval_seconds);

        fs::write(&plist_path, plist_content)?;
        println!("   Created restore plist: {}", plist_path.display());

        let load_result = Command::new("launchctl")
            .args(["load", plist_path.to_str().unwrap_or("")])
            .output();

        if load_result.map(|o| o.status.success()).unwrap_or(false) {
            println!("   Loaded restore agent");
        } else {
            println!("   Warning: Failed to load restore agent");
        }

        Ok(())
    }

    fn uninstall_macos(&self) -> Result<()> {
        let plist_dir = dirs::home_dir()
            .map(|h| h.join("Library/LaunchAgents"))
            .ok_or_else(|| BakerError::Daemon("Cannot find home directory".to_string()))?;

        let backup_plist_path = plist_dir.join(format!("{}.plist", self.backup_service_name));
        let restore_plist_path = plist_dir.join(format!("{}.plist", self.restore_service_name));

        let mut removed = false;

        if backup_plist_path.exists() {
            let _ = Command::new("launchctl")
                .args(["unload", backup_plist_path.to_str().unwrap_or("")])
                .output();
            fs::remove_file(&backup_plist_path)?;
            println!("   Removed: {}", backup_plist_path.display());
            removed = true;
        }

        if restore_plist_path.exists() {
            let _ = Command::new("launchctl")
                .args(["unload", restore_plist_path.to_str().unwrap_or("")])
                .output();
            fs::remove_file(&restore_plist_path)?;
            println!("   Removed: {}", restore_plist_path.display());
            removed = true;
        }

        if !removed {
            println!("   Daemon not installed");
        }

        Ok(())
    }

    fn status_macos(&self) -> Result<()> {
        let plist_dir = dirs::home_dir()
            .map(|h| h.join("Library/LaunchAgents"))
            .ok_or_else(|| BakerError::Daemon("Cannot find home directory".to_string()))?;

        let backup_plist_path = plist_dir.join(format!("{}.plist", self.backup_service_name));
        let restore_plist_path = plist_dir.join(format!("{}.plist", self.restore_service_name));

        let backup_installed = backup_plist_path.exists();
        let restore_installed = restore_plist_path.exists();

        if !backup_installed && !restore_installed {
            println!("No daemons installed");
            return Ok(());
        }

        if backup_installed {
            println!("Backup daemon installed");
            println!("   Plist: {}", backup_plist_path.display());

            let list_result = Command::new("launchctl")
                .args(["list"])
                .output()
                .map(|o| String::from_utf8_lossy(&o.stdout).contains(&self.backup_service_name))
                .unwrap_or(false);

            if list_result {
                println!("   Status: Running");
            } else {
                println!("   Status: Not loaded");
                println!("   Load with: launchctl load {}", backup_plist_path.display());
            }

            let log_path = dirs::home_dir()
                .map(|h| h.join("Library/Logs/baker-backup.log"))
                .unwrap_or_default();
            if log_path.exists() {
                println!("   Logs: {}", log_path.display());
            }
        }

        if restore_installed {
            println!("\nRestore daemon installed");
            println!("   Plist: {}", restore_plist_path.display());

            let list_result = Command::new("launchctl")
                .args(["list"])
                .output()
                .map(|o| String::from_utf8_lossy(&o.stdout).contains(&self.restore_service_name))
                .unwrap_or(false);

            if list_result {
                println!("   Status: Running");
            } else {
                println!("   Status: Not loaded");
                println!("   Load with: launchctl load {}", restore_plist_path.display());
            }

            let log_path = dirs::home_dir()
                .map(|h| h.join("Library/Logs/baker-restore.log"))
                .unwrap_or_default();
            if log_path.exists() {
                println!("   Logs: {}", log_path.display());
            }
        }

        Ok(())
    }

    // ============================================================================
    // Linux (systemd) Implementation
    // ============================================================================

    fn install_linux(&self, schedule: &crate::config::DaemonSchedule) -> Result<()> {
        let systemd_dir = dirs::home_dir()
            .map(|h| h.join(".config/systemd/user"))
            .ok_or_else(|| BakerError::Daemon("Cannot find home directory".to_string()))?;

        let backup_service_path = systemd_dir.join("baker-backup.service");
        let backup_timer_path = systemd_dir.join("baker-backup.timer");

        // Ensure directory exists
        fs::create_dir_all(&systemd_dir)?;

        // Create backup service and timer files
        fs::write(&backup_service_path, self.generate_systemd_service("backup"))?;
        println!("   Created backup service: {}", backup_service_path.display());

        fs::write(
            &backup_timer_path,
            self.generate_systemd_timer("backup", &schedule.every),
        )?;
        println!("   Created backup timer: {}", backup_timer_path.display());

        // Install restore service if enabled
        if schedule.exercise_restore {
            self.install_linux_restore(schedule)?;
        }

        // Reload systemd and enable timer
        let reload = Command::new("systemctl")
            .args(["--user", "daemon-reload"])
            .output();

        let enable = Command::new("systemctl")
            .args(["--user", "enable", "baker-backup.timer"])
            .output();

        let start = Command::new("systemctl")
            .args(["--user", "start", "baker-backup.timer"])
            .output();

        if reload.is_ok() && enable.is_ok() && start.is_ok() {
            println!("   Enabled and started backup timer");

            if schedule.exercise_restore {
                let _ = Command::new("systemctl")
                    .args(["--user", "enable", "baker-restore.timer"])
                    .output();
                let _ = Command::new("systemctl")
                    .args(["--user", "start", "baker-restore.timer"])
                    .output();
                println!("   Enabled and started restore timer");
            }
        } else {
            println!("\n   Warning: Failed to enable timers automatically.");
            println!("   Run these commands manually:");
            println!("   systemctl --user daemon-reload");
            println!("   systemctl --user enable --now baker-backup.timer");
            if schedule.exercise_restore {
                println!("   systemctl --user enable --now baker-restore.timer");
            }
        }

        Ok(())
    }

    fn install_linux_restore(&self, schedule: &crate::config::DaemonSchedule) -> Result<()> {
        let systemd_dir = dirs::home_dir()
            .map(|h| h.join(".config/systemd/user"))
            .ok_or_else(|| BakerError::Daemon("Cannot find home directory".to_string()))?;

        let restore_service_path = systemd_dir.join("baker-restore.service");
        let restore_timer_path = systemd_dir.join("baker-restore.timer");

        fs::write(&restore_service_path, self.generate_systemd_service("restore"))?;
        println!("   Created restore service: {}", restore_service_path.display());

        fs::write(
            &restore_timer_path,
            self.generate_systemd_timer("restore", &schedule.every),
        )?;
        println!("   Created restore timer: {}", restore_timer_path.display());

        Ok(())
    }

    fn uninstall_linux(&self) -> Result<()> {
        let systemd_dir = dirs::home_dir()
            .map(|h| h.join(".config/systemd/user"))
            .ok_or_else(|| BakerError::Daemon("Cannot find home directory".to_string()))?;

        let backup_service_path = systemd_dir.join("baker-backup.service");
        let backup_timer_path = systemd_dir.join("baker-backup.timer");
        let restore_service_path = systemd_dir.join("baker-restore.service");
        let restore_timer_path = systemd_dir.join("baker-restore.timer");

        let mut removed = false;

        if backup_timer_path.exists() || backup_service_path.exists() {
            let _ = Command::new("systemctl")
                .args(["--user", "stop", "baker-backup.timer"])
                .output();
            let _ = Command::new("systemctl")
                .args(["--user", "disable", "baker-backup.timer"])
                .output();

            if backup_service_path.exists() {
                fs::remove_file(&backup_service_path)?;
                println!("   Removed: {}", backup_service_path.display());
            }
            if backup_timer_path.exists() {
                fs::remove_file(&backup_timer_path)?;
                println!("   Removed: {}", backup_timer_path.display());
            }
            removed = true;
        }

        if restore_timer_path.exists() || restore_service_path.exists() {
            let _ = Command::new("systemctl")
                .args(["--user", "stop", "baker-restore.timer"])
                .output();
            let _ = Command::new("systemctl")
                .args(["--user", "disable", "baker-restore.timer"])
                .output();

            if restore_service_path.exists() {
                fs::remove_file(&restore_service_path)?;
                println!("   Removed: {}", restore_service_path.display());
            }
            if restore_timer_path.exists() {
                fs::remove_file(&restore_timer_path)?;
                println!("   Removed: {}", restore_timer_path.display());
            }
            removed = true;
        }

        if removed {
            let _ = Command::new("systemctl")
                .args(["--user", "daemon-reload"])
                .output();
        } else {
            println!("   Daemon not installed");
        }

        Ok(())
    }

    fn status_linux(&self) -> Result<()> {
        let systemd_dir = dirs::home_dir()
            .map(|h| h.join(".config/systemd/user"))
            .ok_or_else(|| BakerError::Daemon("Cannot find home directory".to_string()))?;

        let backup_service_path = systemd_dir.join("baker-backup.service");
        let backup_timer_path = systemd_dir.join("baker-backup.timer");
        let restore_service_path = systemd_dir.join("baker-restore.service");
        let restore_timer_path = systemd_dir.join("baker-restore.timer");

        let backup_installed = backup_service_path.exists() && backup_timer_path.exists();
        let restore_installed = restore_service_path.exists() && restore_timer_path.exists();

        if !backup_installed && !restore_installed {
            println!("No daemons installed");
            return Ok(());
        }

        if backup_installed {
            println!("Backup daemon installed");
            println!("   Service: {}", backup_service_path.display());
            println!("   Timer: {}", backup_timer_path.display());

            println!("\nBackup timer status:");
            if let Ok(output) = Command::new("systemctl")
                .args(["--user", "status", "baker-backup.timer"])
                .output()
            {
                println!("{}", String::from_utf8_lossy(&output.stdout));
            } else {
                println!("   Warning: Failed to get backup timer status");
            }
        }

        if restore_installed {
            println!("\nRestore daemon installed");
            println!("   Service: {}", restore_service_path.display());
            println!("   Timer: {}", restore_timer_path.display());

            println!("\nRestore timer status:");
            if let Ok(output) = Command::new("systemctl")
                .args(["--user", "status", "baker-restore.timer"])
                .output()
            {
                println!("{}", String::from_utf8_lossy(&output.stdout));
            } else {
                println!("   Warning: Failed to get restore timer status");
            }
        }

        Ok(())
    }

    // ============================================================================
    // Windows (Task Scheduler) Implementation
    // ============================================================================

    fn install_windows(&self, schedule: &crate::config::DaemonSchedule) -> Result<()> {
        let interval_seconds = self.parse_interval(&schedule.every)?;
        let interval_minutes = (interval_seconds / time::SECONDS_PER_MINUTE).max(1);

        let config_arg = self
            .config_path
            .as_ref()
            .map(|p| format!("--config \"{}\"", p))
            .unwrap_or_default();

        // Create backup scheduled task
        let backup_result = Command::new("schtasks")
            .args([
                "/Create",
                "/TN",
                windows_tasks::BACKUP,
                "/TR",
                &format!(
                    "\"{}\" backup {}",
                    self.executable_path.display(),
                    config_arg
                ),
                "/SC",
                "MINUTE",
                "/MO",
                &interval_minutes.to_string(),
                "/F",
            ])
            .output();

        if backup_result.map(|o| o.status.success()).unwrap_or(false) {
            println!("   Created backup scheduled task: {}", windows_tasks::BACKUP);
            println!("   Interval: every {} minute(s)", interval_minutes);
        } else {
            return Err(BakerError::Daemon(
                "Failed to create backup scheduled task. Make sure you have appropriate privileges."
                    .to_string(),
            ));
        }

        // Create restore task if enabled
        if schedule.exercise_restore {
            let restore_result = Command::new("schtasks")
                .args([
                    "/Create",
                    "/TN",
                    windows_tasks::RESTORE,
                    "/TR",
                    &format!(
                        "\"{}\" restore {}",
                        self.executable_path.display(),
                        config_arg
                    ),
                    "/SC",
                    "MINUTE",
                    "/MO",
                    &interval_minutes.to_string(),
                    "/F",
                ])
                .output();

            if restore_result.map(|o| o.status.success()).unwrap_or(false) {
                println!("   Created restore scheduled task: {}", windows_tasks::RESTORE);
            } else {
                println!("   Warning: Failed to create restore task");
            }
        }

        Ok(())
    }

    fn uninstall_windows(&self) -> Result<()> {
        let backup_deleted = Command::new("schtasks")
            .args(["/Delete", "/TN", windows_tasks::BACKUP, "/F"])
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);

        if backup_deleted {
            println!("   Deleted backup scheduled task: {}", windows_tasks::BACKUP);
        } else {
            println!("   Backup task not found: {}", windows_tasks::BACKUP);
        }

        let restore_deleted = Command::new("schtasks")
            .args(["/Delete", "/TN", windows_tasks::RESTORE, "/F"])
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);

        if restore_deleted {
            println!("   Deleted restore scheduled task: {}", windows_tasks::RESTORE);
        }

        if !backup_deleted && !restore_deleted {
            println!("   Daemon not installed");
        }

        Ok(())
    }

    fn status_windows(&self) -> Result<()> {
        let backup_result = Command::new("schtasks")
            .args(["/Query", "/TN", windows_tasks::BACKUP, "/FO", "LIST", "/V"])
            .output();

        let backup_installed = backup_result
            .as_ref()
            .map(|o| o.status.success())
            .unwrap_or(false);

        if backup_installed {
            println!("Backup daemon installed\n");
            println!("Backup task details:");
            if let Ok(output) = backup_result {
                println!("{}", String::from_utf8_lossy(&output.stdout));
            }
        } else {
            println!("Backup daemon not installed");
        }

        let restore_result = Command::new("schtasks")
            .args(["/Query", "/TN", windows_tasks::RESTORE, "/FO", "LIST", "/V"])
            .output();

        let restore_installed = restore_result
            .as_ref()
            .map(|o| o.status.success())
            .unwrap_or(false);

        if restore_installed {
            println!("\nRestore daemon installed\n");
            println!("Restore task details:");
            if let Ok(output) = restore_result {
                println!("{}", String::from_utf8_lossy(&output.stdout));
            }
        } else if backup_installed {
            println!("\nRestore daemon not installed");
        }

        if !backup_installed && !restore_installed {
            println!("No daemons installed");
        }

        Ok(())
    }
}