regent-sdk 0.9.1

Multi-paradigm configuration management system as a library
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
//! Service management attribute
//!
//! This module provides the `ServiceBlockExpectedState` type for managing system services.
//!
//! **Compatible OS:**
//! - Linux (all distributions with systemd) - uses `systemctl`
//! - Windows (when `windows` feature is enabled) - uses `sc.exe` and `net` commands
//!
//! # Examples
//!
//! ## Rust API
//!
//! ```no_run
//! use regent_sdk::state::attribute::system::service::{ServiceBlockExpectedState, ServiceExpectedState, ServiceAction};
//! use regent_sdk::{Attribute, ExpectedState, Privilege};
//!
//! // Ensure httpd service is running and enabled
//! let httpd = ServiceBlockExpectedState::state(
//!     "httpd",
//!     ServiceExpectedState::Started,
//!     true
//! );
//!
//! // Just manage service state (running/stopped)
//! let nginx = ServiceBlockExpectedState::state("nginx", ServiceExpectedState::Started, false);
//!
//! // Just manage whether service is enabled at boot
//! let mysql = ServiceBlockExpectedState::enabled("mysql", true);
//!
//! // Manage unconditional action (restart)
//! let redis = ServiceBlockExpectedState::restarted("redis");
//!
//! let expected_state = ExpectedState::new()
//!     .with_attribute(Attribute::service(httpd, Privilege::WithSudo, None))
//!     .build();
//! ```
//!
//! ## YAML API
//!
//! ```yaml
//! Attributes:
//!   - Name: Httpd must be running and enabled
//!     Privilege: !WithSudo
//!     Detail: !Service
//!       Name: httpd
//!       State: Started
//!       Enabled: true
//! ```
//!
//! For state-only configuration:
//!
//! ```yaml
//! Attributes:
//!   - Name: Nginx must be stopped
//!     Privilege: !WithSudo
//!     Detail: !Service
//!       Name: nginx
//!       State: Stopped
//! ```
//!
//! For enabled-only configuration:
//!
//! ```yaml
//! Attributes:
//!   - Name: MySQL must be disabled at boot
//!     Privilege: !WithSudo
//!     Detail: !Service
//!       Name: mysql
//!       Enabled: false
//! ```

use crate::error::RegentError;
use crate::hosts::managed_host::InternalApiCallOutcome;
use crate::hosts::managed_host::{AssessCompliance, ReachCompliance, Timeout};
use crate::hosts::properties::{HostProperties, InitSystem, LinuxFlavor, LinuxSpecifics, OsKind};
use crate::secrets::SecretProvidersPool;
use crate::state::Check;
use crate::state::attribute::HostHandler;
use crate::state::attribute::Privilege;
use crate::state::attribute::Remediation;
use crate::state::attribute::RemediationsList;
use crate::state::compliance::AttributeComplianceAssessment;
use serde::{Deserialize, Serialize};
use std::time::Duration;

/// Desired run-state of the service
///
/// - `Started`  / `Stopped`  — idempotent: only act if the service is not already in the target state.
///
/// # Serialization
///
/// This enum is serialized/deserialized in PascalCase:
/// - `Started` → `"Started"`
/// - `Stopped` → `"Stopped"`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum ServiceExpectedState {
    /// Service should be running
    Started,
    /// Service should be stopped
    Stopped,
}

/// Desired action to run on the service
///
/// - `Restarted`/ `Reloaded` — unconditional: always emit the corresponding systemctl command.
///
/// # Serialization
///
/// This enum is serialized/deserialized in PascalCase:
/// - `Restarted` → `"Restarted"`
/// - `Reloaded` → `"Reloaded"`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum ServiceAction {
    /// Service should be restarted (unconditional action)
    Restarted,
    /// Service should be reloaded (unconditional action)
    Reloaded,
}

/// Configuration for a system service
///
/// This enum represents the desired state for a system service, supporting configurations:
/// - `State`: Manage the service's running state (started/stopped) and/or boot enablement
/// - `Action`: Manage unconditional actions (restart/reload)
///
/// # YAML Representation
///
/// ## State with enabled:
/// ```yaml
/// Name: httpd
/// State: Started
/// Enabled: true
/// ```
///
/// ## State only:
/// ```yaml
/// Name: nginx
/// State: Started
/// ```
///
/// ## Enabled only:
/// ```yaml
/// Name: mysql
/// Enabled: true
/// ```
///
/// ## Action only:
/// ```yaml
/// Name: nginx
/// Action: Restarted
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all_fields = "PascalCase")]
#[serde(untagged)]
pub enum ServiceBlockExpectedState {
    /// Manage the service's running state and/or boot enablement
    ///
    /// Note: The `enabled` field is only present in this variant to respect the semantics
    /// that enabled state is managed alongside running state.
    State {
        /// Name of the service
        name: String,
        /// Desired running state of the service (optional - can be omitted for enabled-only config)
        #[serde(default)]
        state: Option<ServiceExpectedState>,
        /// Whether the service should be enabled at boot
        enabled: bool,
    },
    /// Manage unconditional actions (restart/reload)
    Action {
        /// Name of the service
        name: String,
        /// Action to perform on the service
        action: ServiceAction,
    },
}

impl Timeout for ServiceBlockExpectedState {
    fn default_timeout(&self) -> Duration {
        Duration::from_secs(10)
    }
}

impl ServiceBlockExpectedState {
    /// Create a state configuration with running state and boot enablement
    pub fn state(
        name: &str,
        state: ServiceExpectedState,
        enabled: bool,
    ) -> ServiceBlockExpectedState {
        ServiceBlockExpectedState::State {
            name: name.to_string(),
            state: Some(state),
            enabled,
        }
    }

    /// Create an enabled-only configuration (no state management, only enablement)
    pub fn enabled(name: &str, enabled: bool) -> ServiceBlockExpectedState {
        ServiceBlockExpectedState::State {
            name: name.to_string(),
            state: None,
            enabled,
        }
    }

    /// Create a restarted action configuration
    pub fn restarted(name: &str) -> ServiceBlockExpectedState {
        ServiceBlockExpectedState::Action {
            name: name.to_string(),
            action: ServiceAction::Restarted,
        }
    }

    /// Create a reloaded action configuration
    pub fn reloaded(name: &str) -> ServiceBlockExpectedState {
        ServiceBlockExpectedState::Action {
            name: name.to_string(),
            action: ServiceAction::Reloaded,
        }
    }
}

impl Check for ServiceBlockExpectedState {
    fn check(&self) -> Result<(), RegentError> {
        // if self.state.is_none() && self.enabled.is_none() {
        //     return Err(RegentError::IncoherentExpectedState(
        //         "At least one of State or Enabled must be set.".to_string(),
        //     ));
        // }
        Ok(())
    }

    fn check_host_compatibility(
        &self,
        host_properties: &HostProperties,
    ) -> Result<(), RegentError> {
        use crate::hosts::properties::InitSystem;
        match host_properties.os_kind() {
            OsKind::Linux(linux_specifics) => match linux_specifics.init_system {
                InitSystem::Systemd => Ok(()),
                InitSystem::Unknown => Err(RegentError::IncompatibleHost(
                    "systemctl requires systemd but init system could not be detected".to_string(),
                )),
            },
            #[cfg(feature = "windows")]
            OsKind::Windows(_) => Ok(()),
            incompatible_os_kind => Err(RegentError::IncompatibleHost(format!(
                "Host is {:?} but service management is only supported on Linux with systemd or Windows (with windows feature)",
                incompatible_os_kind
            ))),
        }
    }
}

impl<Handler: HostHandler> AssessCompliance<Handler> for ServiceBlockExpectedState {
    async fn assess_compliance(
        &self,
        host_handler: &mut Handler,
        host_properties: &Option<HostProperties>,
        privilege: &Privilege,
        _optional_secret_provider: &Option<SecretProvidersPool>,
    ) -> Result<AttributeComplianceAssessment, RegentError> {
        // Early check: verify we're on a compatible host
        if let Some(props) = host_properties {
            self.check_host_compatibility(props)?;
        }

        // Determine the effective OS kind - assume Linux if HostProperties is None
        let os_kind = host_properties
            .as_ref()
            .map(|props| props.os_kind())
            .unwrap_or(&OsKind::Linux(LinuxSpecifics {
                linux_flavor: LinuxFlavor::Debian,
                init_system: InitSystem::Systemd,
            }));

        // Check OS-dependent prerequisites
        match os_kind {
            #[cfg(feature = "windows")]
            OsKind::Windows(_) => {
                // Check if sc.exe is available on Windows
                let command_available = host_handler
                    .is_this_command_available("sc", privilege)
                    .await
                    .unwrap_or(false);

                if !command_available {
                    return Err(RegentError::FailedDryRunEvaluation(
                        "Service management commands (sc) are not available on this Windows host"
                            .to_string(),
                    ));
                }
            }
            OsKind::Linux(_) => {
                // Check if systemctl is available on Linux
                let command_available = host_handler
                    .is_this_command_available("systemctl", privilege)
                    .await
                    .unwrap_or(false);

                if !command_available {
                    return Err(RegentError::FailedDryRunEvaluation(
                        "Service management commands (systemctl) are not available on this Linux host".to_string(),
                    ));
                }
            }
            OsKind::FreeBsd(_) | OsKind::MacOs(_) | OsKind::Unknown => {}
        }

        // Match on OS kind to determine service checking behavior
        let mut remediations: Vec<Remediation> = Vec::new();

        match &self {
            Self::State {
                name,
                state,
                enabled,
            } => {
                // Handle state (started/stopped) with optional enabled
                match os_kind {
                    #[cfg(feature = "windows")]
                    OsKind::Windows(_) => {
                        // Handle state if present
                        if let Some(state) = state {
                            match state {
                                ServiceExpectedState::Started => {
                                    let active = windows_service_is_active(host_handler, &name)
                                        .await
                                        .map_err(|e| RegentError::FailedDryRunEvaluation(e))?;
                                    if !active {
                                        remediations.push(Remediation::Service(
                                            ServiceApiCall::from(
                                                ServiceModuleInternalApiCall::Start(name.clone()),
                                                privilege.clone(),
                                            ),
                                        ));
                                    }
                                }
                                ServiceExpectedState::Stopped => {
                                    let active = windows_service_is_active(host_handler, &name)
                                        .await
                                        .map_err(|e| RegentError::FailedDryRunEvaluation(e))?;
                                    if active {
                                        remediations.push(Remediation::Service(
                                            ServiceApiCall::from(
                                                ServiceModuleInternalApiCall::Stop(name.clone()),
                                                privilege.clone(),
                                            ),
                                        ));
                                    }
                                }
                            }
                        }
                        // Handle enabled
                        if *enabled {
                            let is_enabled = windows_service_is_enabled(host_handler, &name)
                                .await
                                .map_err(|e| RegentError::FailedDryRunEvaluation(e))?;
                            if !is_enabled {
                                remediations.push(Remediation::Service(ServiceApiCall::from(
                                    ServiceModuleInternalApiCall::Enable(name.clone()),
                                    privilege.clone(),
                                )));
                            }
                        } else {
                            let is_enabled = windows_service_is_enabled(host_handler, &name)
                                .await
                                .map_err(|e| RegentError::FailedDryRunEvaluation(e))?;
                            if is_enabled {
                                remediations.push(Remediation::Service(ServiceApiCall::from(
                                    ServiceModuleInternalApiCall::Disable(name.clone()),
                                    privilege.clone(),
                                )));
                            }
                        }
                    }
                    OsKind::Linux(_) => {
                        // Handle state if present
                        if let Some(state) = state {
                            match state {
                                ServiceExpectedState::Started => {
                                    let active = service_is_active(host_handler, &name)
                                        .await
                                        .map_err(|e| RegentError::FailedDryRunEvaluation(e))?;
                                    if !active {
                                        remediations.push(Remediation::Service(
                                            ServiceApiCall::from(
                                                ServiceModuleInternalApiCall::Start(name.clone()),
                                                privilege.clone(),
                                            ),
                                        ));
                                    }
                                }
                                ServiceExpectedState::Stopped => {
                                    let active = service_is_active(host_handler, &name)
                                        .await
                                        .map_err(|e| RegentError::FailedDryRunEvaluation(e))?;
                                    if active {
                                        remediations.push(Remediation::Service(
                                            ServiceApiCall::from(
                                                ServiceModuleInternalApiCall::Stop(name.clone()),
                                                privilege.clone(),
                                            ),
                                        ));
                                    }
                                }
                            }
                        }
                        // Handle enabled
                        if *enabled {
                            let is_enabled = service_is_enabled(host_handler, &name)
                                .await
                                .map_err(|e| RegentError::FailedDryRunEvaluation(e))?;
                            if !is_enabled {
                                remediations.push(Remediation::Service(ServiceApiCall::from(
                                    ServiceModuleInternalApiCall::Enable(name.clone()),
                                    privilege.clone(),
                                )));
                            }
                        } else {
                            let is_enabled = service_is_enabled(host_handler, &name)
                                .await
                                .map_err(|e| RegentError::FailedDryRunEvaluation(e))?;
                            if is_enabled {
                                remediations.push(Remediation::Service(ServiceApiCall::from(
                                    ServiceModuleInternalApiCall::Disable(name.clone()),
                                    privilege.clone(),
                                )));
                            }
                        }
                    }
                    OsKind::FreeBsd(_) | OsKind::MacOs(_) | OsKind::Unknown => {
                        return Err(RegentError::FailedDryRunEvaluation(format!(
                            "Service management is not supported on {:?}",
                            os_kind
                        )));
                    }
                }
            }
            Self::Action { name, action } => {
                // Handle unconditional actions (restart/reload)
                match os_kind {
                    #[cfg(feature = "windows")]
                    OsKind::Windows(_) => {
                        match &action {
                            ServiceAction::Restarted => {
                                // Unconditional — always restart.
                                remediations.push(Remediation::Service(ServiceApiCall::from(
                                    ServiceModuleInternalApiCall::Restart(name.clone()),
                                    privilege.clone(),
                                )));
                            }
                            ServiceAction::Reloaded => {
                                // Unconditional — always reload.
                                remediations.push(Remediation::Service(ServiceApiCall::from(
                                    ServiceModuleInternalApiCall::Reload(name.clone()),
                                    privilege.clone(),
                                )));
                            }
                        }
                    }
                    OsKind::Linux(_) => {
                        match &action {
                            ServiceAction::Restarted => {
                                // Unconditional — always restart.
                                remediations.push(Remediation::Service(ServiceApiCall::from(
                                    ServiceModuleInternalApiCall::Restart(name.clone()),
                                    privilege.clone(),
                                )));
                            }
                            ServiceAction::Reloaded => {
                                // Unconditional — always reload.
                                remediations.push(Remediation::Service(ServiceApiCall::from(
                                    ServiceModuleInternalApiCall::Reload(name.clone()),
                                    privilege.clone(),
                                )));
                            }
                        }
                    }
                    OsKind::FreeBsd(_) | OsKind::MacOs(_) | OsKind::Unknown => {
                        return Err(RegentError::FailedDryRunEvaluation(format!(
                            "Service management is not supported on {:?}",
                            os_kind
                        )));
                    }
                }
            }
        }

        if remediations.is_empty() {
            Ok(AttributeComplianceAssessment::Compliant)
        } else {
            Ok(AttributeComplianceAssessment::NonCompliant(
                RemediationsList::from(remediations)?,
            ))
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum ServiceModuleInternalApiCall {
    Start(String),
    Stop(String),
    Restart(String),
    Reload(String),
    Enable(String),
    Disable(String),
}

impl std::fmt::Display for ServiceModuleInternalApiCall {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ServiceModuleInternalApiCall::Start(s) => write!(f, "start {}", s),
            ServiceModuleInternalApiCall::Stop(s) => write!(f, "stop {}", s),
            ServiceModuleInternalApiCall::Restart(s) => write!(f, "restart {}", s),
            ServiceModuleInternalApiCall::Reload(s) => write!(f, "reload {}", s),
            ServiceModuleInternalApiCall::Enable(s) => write!(f, "enable {}", s),
            ServiceModuleInternalApiCall::Disable(s) => write!(f, "disable {}", s),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServiceApiCall {
    pub api_call: ServiceModuleInternalApiCall,
    privilege: Privilege,
}

impl ServiceApiCall {
    pub fn display(&self) -> String {
        match &self.api_call {
            ServiceModuleInternalApiCall::Start(s) => format!("Start service {}", s),
            ServiceModuleInternalApiCall::Stop(s) => format!("Stop service {}", s),
            ServiceModuleInternalApiCall::Restart(s) => format!("Restart service {}", s),
            ServiceModuleInternalApiCall::Reload(s) => format!("Reload service {}", s),
            ServiceModuleInternalApiCall::Enable(s) => format!("Enable service {}", s),
            ServiceModuleInternalApiCall::Disable(s) => format!("Disable service {}", s),
        }
    }

    fn from(api_call: ServiceModuleInternalApiCall, privilege: Privilege) -> ServiceApiCall {
        ServiceApiCall {
            api_call,
            privilege,
        }
    }
}

impl Check for ServiceApiCall {
    fn check(&self) -> Result<(), RegentError> {
        Ok(())
    }

    fn check_host_compatibility(
        &self,
        host_properties: &HostProperties,
    ) -> Result<(), RegentError> {
        use crate::hosts::properties::InitSystem;
        match host_properties.os_kind() {
            OsKind::Linux(linux_specifics) => match linux_specifics.init_system {
                InitSystem::Systemd => Ok(()),
                InitSystem::Unknown => Err(RegentError::IncompatibleHost(
                    "systemctl requires systemd but init system could not be detected".to_string(),
                )),
            },
            #[cfg(feature = "windows")]
            OsKind::Windows(_) => Ok(()),
            incompatible_os_kind => Err(RegentError::IncompatibleHost(format!(
                "Host is {:?} but service management is only supported on Linux with systemd or Windows (with windows feature)",
                incompatible_os_kind
            ))),
        }
    }
}

impl<Handler: HostHandler> ReachCompliance<Handler> for ServiceApiCall {
    async fn call(
        &self,
        host_handler: &mut Handler,
        host_properties: &Option<HostProperties>,
        _optional_secret_provider: &Option<SecretProvidersPool>,
    ) -> Result<InternalApiCallOutcome, RegentError> {
        // Early check: verify we're on a compatible host
        if let Some(props) = host_properties {
            self.check_host_compatibility(props)?;
        }

        // Determine the effective OS kind - assume Linux if HostProperties is None
        let os_kind = host_properties
            .as_ref()
            .map(|props| props.os_kind())
            .unwrap_or(&OsKind::Linux(LinuxSpecifics {
                linux_flavor: LinuxFlavor::Debian,
                init_system: InitSystem::Systemd,
            }));

        // Match on OS kind to execute the appropriate command
        match os_kind {
            #[cfg(feature = "windows")]
            OsKind::Windows(_) => {
                // Build Windows command
                let cmd = match &self.api_call {
                    ServiceModuleInternalApiCall::Start(s) => format!("net start {}", s),
                    ServiceModuleInternalApiCall::Stop(s) => format!("net stop {}", s),
                    ServiceModuleInternalApiCall::Restart(s) => {
                        // Windows doesn't have a direct restart command, we stop then start
                        format!("net stop {} && net start {}", s, s)
                    }
                    ServiceModuleInternalApiCall::Reload(s) => {
                        // Windows doesn't have a direct reload command
                        // This might not be supported for all services
                        format!("sc control {} 128", s) // Sends a reload parameter, but not all services support this
                    }
                    ServiceModuleInternalApiCall::Enable(s) => {
                        format!("sc config {} start= auto", s)
                    }
                    ServiceModuleInternalApiCall::Disable(s) => {
                        format!("sc config {} start= disabled", s)
                    }
                };

                // Execute Windows command
                let result = host_handler.run_windows_command(&cmd).await;

                match result {
                    Ok(result) => {
                        if result.return_code == 0 {
                            Ok(InternalApiCallOutcome::Success(None))
                        } else {
                            Ok(InternalApiCallOutcome::Failure(format!(
                                "RC: {}, STDOUT: {}, STDERR: {}",
                                result.return_code, result.stdout, result.stderr
                            )))
                        }
                    }
                    Err(e) => Ok(InternalApiCallOutcome::Failure(format!(
                        "Command execution failed: {:?}",
                        e
                    ))),
                }
            }
            OsKind::Linux(_) => {
                // Build Linux command
                let cmd = match &self.api_call {
                    ServiceModuleInternalApiCall::Start(s) => format!("systemctl start {}", s),
                    ServiceModuleInternalApiCall::Stop(s) => format!("systemctl stop {}", s),
                    ServiceModuleInternalApiCall::Restart(s) => format!("systemctl restart {}", s),
                    ServiceModuleInternalApiCall::Reload(s) => format!("systemctl reload {}", s),
                    ServiceModuleInternalApiCall::Enable(s) => format!("systemctl enable {}", s),
                    ServiceModuleInternalApiCall::Disable(s) => format!("systemctl disable {}", s),
                };

                // Execute Linux command
                let result = host_handler.run_command(&cmd, &self.privilege).await;

                match result {
                    Ok(result) => {
                        if result.return_code == 0 {
                            Ok(InternalApiCallOutcome::Success(None))
                        } else {
                            Ok(InternalApiCallOutcome::Failure(format!(
                                "RC: {}, STDOUT: {}, STDERR: {}",
                                result.return_code, result.stdout, result.stderr
                            )))
                        }
                    }
                    Err(e) => Ok(InternalApiCallOutcome::Failure(format!(
                        "Command execution failed: {:?}",
                        e
                    ))),
                }
            }
            OsKind::FreeBsd(_) | OsKind::MacOs(_) | OsKind::Unknown => {
                Err(RegentError::FailedDryRunEvaluation(format!(
                    "Service management is not supported on {:?}",
                    os_kind
                )))
            }
        }
    }
}

async fn service_is_active<Handler: HostHandler>(
    host_handler: &mut Handler,
    name: &str,
) -> Result<bool, String> {
    match host_handler
        .run_command(&format!("systemctl is-active {}", name), &Privilege::None)
        .await
    {
        Ok(r) => match r.return_code {
            0 => Ok(true),
            3 => Ok(false),
            4 => Err(format!("Service not found: {}", name)),
            _ => Ok(false), // "failed" or other transient states → not active
        },
        Err(e) => Err(format!("Unable to check active state of {}: {:?}", name, e)),
    }
}

async fn service_is_enabled<Handler: HostHandler>(
    host_handler: &mut Handler,
    name: &str,
) -> Result<bool, String> {
    match host_handler
        .run_command(&format!("systemctl is-enabled {}", name), &Privilege::None)
        .await
    {
        Ok(r) => match r.return_code {
            0 => Ok(true),
            1 | 3 => Ok(false),
            4 => Err(format!("Service not found: {}", name)),
            _ => Ok(false),
        },
        Err(e) => Err(format!(
            "Unable to check enabled state of {}: {:?}",
            name, e
        )),
    }
}

#[cfg(feature = "windows")]
async fn windows_service_is_active<Handler: HostHandler>(
    host_handler: &mut Handler,
    name: &str,
) -> Result<bool, String> {
    match host_handler
        .run_windows_command(&format!("sc query {}", name))
        .await
    {
        Ok(r) => {
            // sc query returns 0 for success, but we need to parse the output
            // The output contains "STATE" line which shows the service state
            if r.return_code != 0 {
                // Service might not exist or other error
                if r.stdout.contains("does not exist") || r.stderr.contains("does not exist") {
                    return Err(format!("Service not found: {}", name));
                }
                return Ok(false);
            }

            // Parse the output for service state
            // Looking for lines like: "STATE              : 4  RUNNING"
            let output = r.stdout.to_lowercase();
            if output.contains("running") {
                Ok(true)
            } else if output.contains("stopped") || output.contains("pending") {
                Ok(false)
            } else {
                // Default to false if we can't determine the state
                Ok(false)
            }
        }
        Err(e) => Err(format!("Unable to check active state of {}: {:?}", name, e)),
    }
}

#[cfg(feature = "windows")]
async fn windows_service_is_enabled<Handler: HostHandler>(
    host_handler: &mut Handler,
    name: &str,
) -> Result<bool, String> {
    match host_handler
        .run_windows_command(&format!("sc qc {}", name))
        .await
    {
        Ok(r) => {
            // sc qc (query configuration) returns information about the service
            // We need to look for the START_TYPE line
            if r.return_code != 0 {
                if r.stdout.contains("does not exist") || r.stderr.contains("does not exist") {
                    return Err(format!("Service not found: {}", name));
                }
                return Ok(false);
            }

            // Parse the output for start type
            // Looking for lines like: "START_TYPE       : 2   AUTO_START"
            let output = r.stdout.to_lowercase();
            if output.contains("auto_start") || output.contains("2") {
                Ok(true)
            } else if output.contains("disabled") || output.contains("3") || output.contains("4") {
                Ok(false)
            } else {
                // Default to false if we can't determine
                Ok(false)
            }
        }
        Err(e) => Err(format!(
            "Unable to check enabled state of {}: {:?}",
            name, e
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parsing_service_module_block_from_yaml_str() {
        let raw = "---
- Name: nginx
  State: Started
  Enabled: true

- Name: nginx
  State: Stopped
  Enabled: false

- Name: nginx
  Action: Restarted

- Name: nginx
  Action: Reloaded

- Name: nginx
  Enabled: true
        ";
        let _: Vec<ServiceBlockExpectedState> = yaml_serde::from_str(raw).unwrap();
    }
}