greggd 1.0.3

Lightweight Linux, macOS, and Windows metrics daemon that exposes a read-only JSON API for the gregg client.
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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
//! CLI argument parsing and subcommand dispatch for `greggd`.
//!
//! Uses `clap` derive macros for structured argument parsing. Each
//! subcommand has a stable help message and returns a meaningful exit code.

use std::fmt;
use std::net::IpAddr;
use std::path::PathBuf;

use clap::{Parser, Subcommand};

use crate::config::{Config, ConfigError};
use crate::service::{ServiceError, ServiceManager};

/// Lightweight metrics daemon for the gregg monitoring system.
#[derive(Parser)]
#[command(
    name = "greggd",
    version,
    about = "Lightweight Linux, macOS, and Windows metrics daemon",
    long_about = "greggd runs on designated systems and exposes a read-only JSON API \
                  for the gregg terminal client. It samples CPU, memory, swap, and \
                  load metrics on a configurable interval and serves cached immutable \
                  snapshots over HTTP/1."
)]
pub struct Cli {
    /// Path to the configuration file.
    #[arg(
        long,
        short = 'c',
        global = true,
        help = "Path to the TOML configuration file",
        value_name = "PATH"
    )]
    pub config: Option<PathBuf>,

    #[command(subcommand)]
    pub command: Command,
}

/// Available subcommands.
#[derive(Subcommand)]
pub enum Command {
    /// Run the daemon in the foreground.
    Run,
    /// Start the greggd system service.
    Start,
    /// Stop the greggd system service.
    Stop,
    /// Restart the greggd system service.
    Restart,
    /// Idempotent service check: starts the service if not active.
    Croncheck,
    /// Update the bind address and restart the service.
    Host {
        /// The new IPv4 or IPv6 address to bind to.
        address: IpAddr,
    },
    /// Update the TCP port and restart the service.
    Port {
        /// The new port number (1-65535).
        port: u16,
    },
    /// Internal: Windows SCM service entry point. Not for interactive use.
    #[command(hide = true)]
    Service,
}

/// Exit codes returned by greggd commands.
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExitCode {
    Success = 0,
    /// Configuration error (invalid, missing, or unwritable).
    ConfigError = 1,
    /// Service management command failed.
    ServiceError = 2,
    /// The daemon could not start (port conflict, etc.).
    RuntimeError = 3,
    /// Permission denied for the requested operation.
    PermissionDenied = 4,
}

impl From<&ConfigError> for ExitCode {
    fn from(e: &ConfigError) -> Self {
        match e {
            ConfigError::Io { source, .. }
                if source.kind() == std::io::ErrorKind::PermissionDenied =>
            {
                Self::PermissionDenied
            }
            ConfigError::AtomicWrite { source, .. } => match source {
                crate::config::AtomicWriteError::Io(io)
                    if io.kind() == std::io::ErrorKind::PermissionDenied =>
                {
                    Self::PermissionDenied
                }
                _ => Self::ConfigError,
            },
            _ => Self::ConfigError,
        }
    }
}

impl From<&ServiceError> for ExitCode {
    fn from(e: &ServiceError) -> Self {
        match e {
            ServiceError::CommandFailed { .. }
            | ServiceError::ExecFailed { .. }
            | ServiceError::NotAvailable { .. }
            | ServiceError::StateQueryFailed { .. }
            | ServiceError::Timeout { .. } => Self::ServiceError,
            ServiceError::AccessDenied => Self::PermissionDenied,
        }
    }
}

/// Resolve the config path: explicit `--config` or platform default.
pub fn resolve_config_path(explicit: Option<&PathBuf>) -> PathBuf {
    explicit.cloned().unwrap_or_else(Config::default_path)
}

/// Load or create the configuration.
///
/// If the config file exists, load and validate it. If it does not exist
/// and no explicit path was given, use defaults. If an explicit path was
/// given but the file is missing, return an error.
pub fn load_config(path: &std::path::Path, explicit: bool) -> Result<Config, ConfigError> {
    if path.exists() {
        Config::load(path)
    } else if explicit {
        Err(ConfigError::Io {
            path: path.to_path_buf(),
            source: std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("configuration file not found: {}", path.display()),
            ),
        })
    } else {
        // No explicit path and file doesn't exist — use defaults.
        Ok(Config::default())
    }
}

/// Error returned when config validation fails during mutation.
///
/// This is separate from `ConfigError` because it carries the violations
/// for structured reporting and requires a distinct exit code.
#[derive(Debug)]
pub struct ConfigValidationError(pub Vec<crate::config::ConfigViolation>);

impl fmt::Display for ConfigValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "configuration validation failed:")?;
        for v in &self.0 {
            write!(f, "\n  - {v}")?;
        }
        Ok(())
    }
}

impl std::error::Error for ConfigValidationError {}

/// Update a single field in the config and atomically persist it.
///
/// This is the shared logic for `host` and `port` subcommands.
pub fn mutate_and_restart(
    path: &std::path::Path,
    explicit: bool,
    mutate: impl FnOnce(&mut Config),
    service: &dyn ServiceManager,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut config = load_config(path, explicit)?;
    mutate(&mut config);

    let violations = config.validate();
    if !violations.is_empty() {
        return Err(Box::new(ConfigValidationError(violations)));
    }

    config.write_atomic(path)?;

    service
        .restart()
        .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;

    Ok(())
}

/// Dispatch a subcommand using the path's current existence as a compatibility
/// fallback. The binary entry point uses [`dispatch_with_config_intent`] so a
/// missing explicit path remains distinguishable from a missing default path.
///
/// # Errors
///
/// Returns an error if the command fails.
pub fn dispatch(
    command: &Command,
    config_path: &std::path::Path,
    service: &dyn ServiceManager,
) -> Result<(), Box<dyn std::error::Error>> {
    dispatch_with_config_intent(command, config_path, config_path.exists(), service)
}

/// Dispatch a command while preserving whether the config path was explicit.
pub fn dispatch_with_config_intent(
    command: &Command,
    config_path: &std::path::Path,
    explicit: bool,
    service: &dyn ServiceManager,
) -> Result<(), Box<dyn std::error::Error>> {
    match command {
        Command::Run => {
            // Delegate to the async run entry point.
            // This is handled in main.rs.
            unreachable!("Command::Run is handled in main.rs")
        }
        Command::Start => {
            service
                .start()
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;
            Ok(())
        }
        Command::Stop => {
            service
                .stop()
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;
            Ok(())
        }
        Command::Restart => {
            service
                .restart()
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;
            Ok(())
        }
        Command::Croncheck => match service.is_active() {
            Ok(true) => {
                // Already active — idempotent success.
                Ok(())
            }
            Ok(false) => {
                // Not active — start it.
                service
                    .start()
                    .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;
                Ok(())
            }
            Err(e) => Err(Box::new(e)),
        },
        Command::Host { address } => mutate_and_restart(
            config_path,
            explicit,
            |config| {
                config.host = *address;
            },
            service,
        ),
        Command::Port { port } => mutate_and_restart(
            config_path,
            explicit,
            |config| {
                config.port = *port;
            },
            service,
        ),
        Command::Service => {
            unreachable!("Command::Service is handled in main.rs")
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;
    use std::sync::Mutex;

    /// A fake service manager that records all calls and allows
    /// controlling `is_active` and error behavior.
    #[derive(Debug)]
    struct FakeServiceManager {
        active: Mutex<bool>,
        /// Record of all method calls made.
        calls: Mutex<Vec<&'static str>>,
        /// If set, `start` returns this error.
        start_error: Mutex<Option<ServiceError>>,
        /// If set, `restart` returns this error.
        restart_error: Mutex<Option<ServiceError>>,
        /// If set, `is_active` returns this error.
        is_active_error: Mutex<Option<ServiceError>>,
    }

    impl FakeServiceManager {
        fn new() -> Self {
            Self {
                active: Mutex::new(false),
                calls: Mutex::new(Vec::new()),
                start_error: Mutex::new(None),
                restart_error: Mutex::new(None),
                is_active_error: Mutex::new(None),
            }
        }

        fn set_active(&self, active: bool) {
            *self.active.lock().unwrap() = active;
        }

        fn set_start_error(&self, err: ServiceError) {
            *self.start_error.lock().unwrap() = Some(err);
        }

        fn set_restart_error(&self, err: ServiceError) {
            *self.restart_error.lock().unwrap() = Some(err);
        }

        fn set_is_active_error(&self, err: ServiceError) {
            *self.is_active_error.lock().unwrap() = Some(err);
        }

        fn calls(&self) -> Vec<&'static str> {
            self.calls.lock().unwrap().clone()
        }
    }

    impl ServiceManager for FakeServiceManager {
        fn start(&self) -> Result<(), ServiceError> {
            self.calls.lock().unwrap().push("start");
            if let Some(err) = self.start_error.lock().unwrap().take() {
                return Err(err);
            }
            *self.active.lock().unwrap() = true;
            Ok(())
        }

        fn stop(&self) -> Result<(), ServiceError> {
            self.calls.lock().unwrap().push("stop");
            *self.active.lock().unwrap() = false;
            Ok(())
        }

        fn restart(&self) -> Result<(), ServiceError> {
            self.calls.lock().unwrap().push("restart");
            if let Some(err) = self.restart_error.lock().unwrap().take() {
                return Err(err);
            }
            Ok(())
        }

        fn is_active(&self) -> Result<bool, ServiceError> {
            self.calls.lock().unwrap().push("is_active");
            if let Some(err) = self.is_active_error.lock().unwrap().take() {
                return Err(err);
            }
            Ok(*self.active.lock().unwrap())
        }
    }

    // --- CLI parsing tests ---

    #[test]
    fn cli_parses_run_command() {
        let cli = Cli::try_parse_from(["greggd", "run"]).unwrap();
        assert!(matches!(cli.command, Command::Run));
        assert!(cli.config.is_none());
    }

    #[test]
    fn cli_parses_start_command() {
        let cli = Cli::try_parse_from(["greggd", "start"]).unwrap();
        assert!(matches!(cli.command, Command::Start));
    }

    #[test]
    fn cli_parses_stop_command() {
        let cli = Cli::try_parse_from(["greggd", "stop"]).unwrap();
        assert!(matches!(cli.command, Command::Stop));
    }

    #[test]
    fn cli_parses_restart_command() {
        let cli = Cli::try_parse_from(["greggd", "restart"]).unwrap();
        assert!(matches!(cli.command, Command::Restart));
    }

    #[test]
    fn cli_parses_croncheck_command() {
        let cli = Cli::try_parse_from(["greggd", "croncheck"]).unwrap();
        assert!(matches!(cli.command, Command::Croncheck));
    }

    #[test]
    fn cli_parses_service_command() {
        let cli = Cli::try_parse_from(["greggd", "service"]).unwrap();
        assert!(matches!(cli.command, Command::Service));
    }

    #[test]
    fn cli_parses_host_command() {
        let cli = Cli::try_parse_from(["greggd", "host", "127.0.0.1"]).unwrap();
        match cli.command {
            Command::Host { address } => {
                assert_eq!(address, "127.0.0.1".parse::<IpAddr>().unwrap());
            }
            _ => panic!("expected Host command"),
        }
    }

    #[test]
    fn cli_parses_port_command() {
        let cli = Cli::try_parse_from(["greggd", "port", "11320"]).unwrap();
        match cli.command {
            Command::Port { port } => assert_eq!(port, 11320),
            _ => panic!("expected Port command"),
        }
    }

    #[test]
    fn cli_parses_config_flag() {
        let cli = Cli::try_parse_from(["greggd", "--config", "/tmp/test.toml", "run"]).unwrap();
        assert_eq!(cli.config, Some(PathBuf::from("/tmp/test.toml")));
    }

    // --- Config resolution tests ---

    #[test]
    fn resolve_config_path_explicit() {
        let explicit = PathBuf::from("/custom/path.toml");
        let resolved = resolve_config_path(Some(&explicit));
        assert_eq!(resolved, explicit);
    }

    #[test]
    fn resolve_config_path_default() {
        let resolved = resolve_config_path(None);
        assert_eq!(resolved, Config::default_path());
    }

    #[test]
    fn load_config_from_existing_file() {
        let dir = std::env::temp_dir().join("greggd_test_cli_load");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");

        let config = Config::default();
        config.write_atomic(&path).unwrap();

        let loaded = load_config(&path, true).unwrap();
        assert_eq!(config, loaded);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_config_explicit_missing_file_errors() {
        let path = PathBuf::from("/nonexistent/greggd.toml");
        let result = load_config(&path, true);
        assert!(result.is_err());
    }

    #[test]
    fn load_config_implicit_missing_file_uses_defaults() {
        let path = PathBuf::from("/nonexistent/greggd.toml");
        let config = load_config(&path, false).unwrap();
        assert_eq!(config, Config::default());
    }

    // --- Exit code tests ---

    #[test]
    fn exit_code_from_config_error() {
        let err = ConfigError::Io {
            path: PathBuf::from("test"),
            source: std::io::Error::new(std::io::ErrorKind::NotFound, "not found"),
        };
        let code = ExitCode::from(&err);
        assert_eq!(code, ExitCode::ConfigError);
    }

    #[test]
    fn exit_code_from_permission_denied_io() {
        let err = ConfigError::Io {
            path: PathBuf::from("/etc/gregg/greggd.toml"),
            source: std::io::Error::new(std::io::ErrorKind::PermissionDenied, "permission denied"),
        };
        let code = ExitCode::from(&err);
        assert_eq!(code, ExitCode::PermissionDenied);
    }

    #[test]
    fn exit_code_from_permission_denied_atomic_write() {
        let err = ConfigError::AtomicWrite {
            path: PathBuf::from("/etc/gregg/greggd.toml"),
            source: crate::config::AtomicWriteError::Io(std::io::Error::new(
                std::io::ErrorKind::PermissionDenied,
                "permission denied",
            )),
        };
        let code = ExitCode::from(&err);
        assert_eq!(code, ExitCode::PermissionDenied);
    }

    #[test]
    fn exit_code_from_service_error() {
        let err = ServiceError::CommandFailed {
            command: "test".into(),
            exit_status: Some(1),
            stderr: String::new(),
        };
        let code = ExitCode::from(&err);
        assert_eq!(code, ExitCode::ServiceError);
    }

    // --- Croncheck behavioral tests ---

    #[test]
    fn croncheck_active_does_nothing() {
        let service = FakeServiceManager::new();
        service.set_active(true);

        let result = dispatch(&Command::Croncheck, Path::new("/dev/null"), &service);
        assert!(result.is_ok());

        let calls = service.calls();
        assert_eq!(calls, vec!["is_active"]);
        // Should NOT call start since service is already active.
    }

    #[test]
    fn croncheck_inactive_starts_service() {
        let service = FakeServiceManager::new();
        service.set_active(false);

        let result = dispatch(&Command::Croncheck, Path::new("/dev/null"), &service);
        assert!(result.is_ok());

        let calls = service.calls();
        assert_eq!(calls, vec!["is_active", "start"]);
    }

    #[test]
    fn croncheck_error_returns_error() {
        let service = FakeServiceManager::new();
        service.set_is_active_error(ServiceError::StateQueryFailed {
            source: std::io::Error::other("query failed"),
        });

        let result = dispatch(&Command::Croncheck, Path::new("/dev/null"), &service);
        assert!(result.is_err());

        let calls = service.calls();
        assert_eq!(calls, vec!["is_active"]);
        // Should NOT call start on error.
    }

    #[test]
    fn croncheck_active_with_noop_manager() {
        let service = FakeServiceManager::new();
        // FakeServiceManager defaults to inactive, so croncheck will try to start.
        // start() succeeds silently by default.
        let result = dispatch(&Command::Croncheck, Path::new("/dev/null"), &service);
        assert!(result.is_ok());
        assert_eq!(service.calls(), vec!["is_active", "start"]);
    }

    // --- Start/stop/restart dispatch tests ---

    #[test]
    fn start_dispatch_calls_service_start() {
        let service = FakeServiceManager::new();
        let result = dispatch(&Command::Start, Path::new("/dev/null"), &service);
        assert!(result.is_ok());
        assert_eq!(service.calls(), vec!["start"]);
    }

    #[test]
    fn stop_dispatch_calls_service_stop() {
        let service = FakeServiceManager::new();
        let result = dispatch(&Command::Stop, Path::new("/dev/null"), &service);
        assert!(result.is_ok());
        assert_eq!(service.calls(), vec!["stop"]);
    }

    #[test]
    fn restart_dispatch_calls_service_restart() {
        let service = FakeServiceManager::new();
        let result = dispatch(&Command::Restart, Path::new("/dev/null"), &service);
        assert!(result.is_ok());
        assert_eq!(service.calls(), vec!["restart"]);
    }

    #[test]
    fn start_dispatch_error_returns_error() {
        let service = FakeServiceManager::new();
        service.set_start_error(ServiceError::CommandFailed {
            command: "systemctl start greggd".into(),
            exit_status: Some(1),
            stderr: "unit not found".into(),
        });

        let result = dispatch(&Command::Start, Path::new("/dev/null"), &service);
        assert!(result.is_err());
    }

    #[test]
    fn restart_dispatch_error_returns_error() {
        let service = FakeServiceManager::new();
        service.set_restart_error(ServiceError::CommandFailed {
            command: "systemctl restart greggd".into(),
            exit_status: Some(1),
            stderr: "unit not found".into(),
        });

        let result = dispatch(&Command::Restart, Path::new("/dev/null"), &service);
        assert!(result.is_err());
    }

    // --- Host/port mutation tests ---

    #[test]
    fn implicit_missing_config_starts_from_defaults() {
        let dir = std::env::temp_dir().join("greggd_test_cli_implicit_missing");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        let service = FakeServiceManager::new();

        dispatch_with_config_intent(&Command::Port { port: 11320 }, &path, false, &service)
            .unwrap();

        assert_eq!(Config::load(&path).unwrap().port, 11320);
        assert_eq!(service.calls(), vec!["restart"]);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn explicit_missing_config_does_not_write_or_restart() {
        let dir = std::env::temp_dir().join("greggd_test_cli_explicit_missing");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        let service = FakeServiceManager::new();

        let result = dispatch_with_config_intent(
            &Command::Host {
                address: "127.0.0.1".parse().unwrap(),
            },
            &path,
            true,
            &service,
        );

        assert!(result.is_err());
        assert!(!path.exists());
        assert!(service.calls().is_empty());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn host_mutation_persists_and_restarts() {
        let dir = std::env::temp_dir().join("greggd_test_cli_host_mutate");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");

        // Write initial config.
        let config = Config::default();
        config.write_atomic(&path).unwrap();

        let service = FakeServiceManager::new();
        let new_addr: IpAddr = "127.0.0.1".parse().unwrap();

        let result = dispatch(&Command::Host { address: new_addr }, &path, &service);
        assert!(result.is_ok());

        // Verify the file was updated.
        let loaded = Config::load(&path).unwrap();
        assert_eq!(loaded.host, new_addr);

        // Verify restart was called.
        let calls = service.calls();
        assert!(calls.contains(&"restart"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn port_mutation_persists_and_restarts() {
        let dir = std::env::temp_dir().join("greggd_test_cli_port_mutate");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");

        // Write initial config.
        let config = Config::default();
        config.write_atomic(&path).unwrap();

        let service = FakeServiceManager::new();

        let result = dispatch(&Command::Port { port: 11320 }, &path, &service);
        assert!(result.is_ok());

        // Verify the file was updated.
        let loaded = Config::load(&path).unwrap();
        assert_eq!(loaded.port, 11320);

        // Verify restart was called.
        let calls = service.calls();
        assert!(calls.contains(&"restart"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn host_mutation_validates_before_persisting() {
        let dir = std::env::temp_dir().join("greggd_test_cli_host_validate");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");

        let config = Config::default();
        config.write_atomic(&path).unwrap();

        let service = FakeServiceManager::new();

        // Mutate to invalid state (empty name) — validation should fail.
        let result = mutate_and_restart(
            &path,
            true,
            |config| {
                config.name = String::new();
            },
            &service,
        );

        // Should fail due to validation.
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.downcast_ref::<ConfigValidationError>().is_some());

        // The original config should be unchanged.
        let loaded = Config::load(&path).unwrap();
        assert_eq!(loaded.name, "greggd");

        // restart should NOT have been called.
        assert!(!service.calls().contains(&"restart"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn mutation_does_not_restart_on_write_failure() {
        let dir = std::env::temp_dir().join("greggd_test_cli_no_restart");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");

        let config = Config::default();
        config.write_atomic(&path).unwrap();

        let service = FakeServiceManager::new();

        // Try to write to a path that will fail (nonexistent parent).
        let result = mutate_and_restart(
            Path::new("/nonexistent_dir/config.toml"),
            true,
            |config| {
                config.port = 11320;
            },
            &service,
        );

        assert!(result.is_err());

        // restart should NOT have been called.
        let calls = service.calls();
        assert!(!calls.contains(&"restart"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn mutation_restart_failure_returns_error() {
        let dir = std::env::temp_dir().join("greggd_test_cli_restart_fail");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");

        let config = Config::default();
        config.write_atomic(&path).unwrap();

        let service = FakeServiceManager::new();
        service.set_restart_error(ServiceError::CommandFailed {
            command: "systemctl restart greggd".into(),
            exit_status: Some(1),
            stderr: "failed".into(),
        });

        let result = dispatch(&Command::Port { port: 11320 }, &path, &service);

        assert!(result.is_err());

        // The file SHOULD have been written (persistence succeeded).
        let loaded = Config::load(&path).unwrap();
        assert_eq!(loaded.port, 11320);

        let _ = std::fs::remove_dir_all(&dir);
    }

    // --- Path-with-spaces test ---

    #[test]
    fn write_atomic_works_with_spaces_in_path() {
        let dir = std::env::temp_dir().join("greggd test with spaces");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config file.toml");

        let config = Config::default();
        config.write_atomic(&path).unwrap();

        let loaded = Config::load(&path).unwrap();
        assert_eq!(config, loaded);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_config_explicit_missing_file_errors_display() {
        let path = PathBuf::from("/nonexistent/greggd.toml");
        let result = load_config(&path, true);
        assert!(result.is_err());
        let err = result.unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("configuration file not found"));
    }

    // --- Service restart loop protection tests ---

    #[test]
    fn croncheck_with_failing_start_returns_error_without_looping() {
        // When the service is inactive and start fails, croncheck must
        // return an error after a single start attempt, not loop.
        let service = FakeServiceManager::new();
        service.set_active(false);
        service.set_start_error(ServiceError::CommandFailed {
            command: "systemctl start greggd".into(),
            exit_status: Some(1),
            stderr: "invalid config".into(),
        });

        let result = dispatch(&Command::Croncheck, Path::new("/dev/null"), &service);
        assert!(result.is_err());

        // Exactly one is_active + one start call, no loop.
        let calls = service.calls();
        assert_eq!(calls, vec!["is_active", "start"]);
    }

    #[test]
    fn repeated_croncheck_calls_each_make_single_start_attempt() {
        // Simulate a cron daemon calling croncheck every minute while the
        // service is inactive and start keeps failing. Each invocation
        // should be independent: one is_active + one start per call.
        for i in 0..5 {
            let service = FakeServiceManager::new();
            service.set_active(false);
            service.set_start_error(ServiceError::CommandFailed {
                command: "systemctl start greggd".into(),
                exit_status: Some(1),
                stderr: format!("attempt {i}"),
            });

            let result = dispatch(&Command::Croncheck, Path::new("/dev/null"), &service);
            assert!(result.is_err(), "iteration {i} should fail");

            let calls = service.calls();
            assert_eq!(
                calls,
                vec!["is_active", "start"],
                "iteration {i} should have exactly 2 calls"
            );
        }
    }

    #[test]
    fn croncheck_start_success_sets_active_and_does_not_restart() {
        // When croncheck starts the service successfully, it should not
        // call restart. Only start should be called.
        let service = FakeServiceManager::new();
        service.set_active(false);

        let result = dispatch(&Command::Croncheck, Path::new("/dev/null"), &service);
        assert!(result.is_ok());

        let calls = service.calls();
        assert_eq!(calls, vec!["is_active", "start"]);
        assert!(!calls.contains(&"restart"));
    }
}