Skip to main content

hyprstream_core/cli/
systemd_setup.rs

1//! Systemd unit installation for socket activation
2//!
3//! This module provides automatic installation of systemd user units
4//! for the service socket activation pattern.
5//!
6//! # Usage
7//!
8//! ```ignore
9//! use hyprstream::cli::systemd_setup::ensure_units;
10//!
11//! let services = &["registry".to_owned(), "policy".to_owned()];
12//! if ensure_units(services) {
13//!     // Systemd units are installed and ready
14//! }
15//! ```
16
17use tracing::info;
18
19/// Check if systemd is available
20pub fn is_systemd_available() -> bool {
21    hyprstream_rpc::has_systemd()
22}
23
24/// Ensure systemd socket units are installed and enabled (idempotent)
25///
26/// # Arguments
27///
28/// * `services` - List of services to ensure.
29///
30/// Returns `true` if sockets are ready for use.
31pub fn ensure_units(services: &[String]) -> bool {
32    if !is_systemd_available() {
33        return false;
34    }
35
36    // Convert String slices to &str for ServiceManager
37    let services_list: Vec<&str> = services.iter().map(std::string::String::as_str).collect();
38
39    // Create a runtime for async ServiceManager operations
40    let rt = match tokio::runtime::Builder::new_current_thread()
41        .enable_all()
42        .build()
43    {
44        Ok(rt) => rt,
45        Err(e) => {
46            tracing::warn!("Failed to create runtime for systemd setup: {}", e);
47            return false;
48        }
49    };
50
51    rt.block_on(async {
52        let manager = match hyprstream_service::detect_service_manager().await {
53            Ok(m) => m,
54            Err(e) => {
55                tracing::warn!("Failed to detect service manager: {}", e);
56                return false;
57            }
58        };
59
60        // Install and start all services
61        for service in services_list {
62            if let Err(e) = manager.ensure(service).await {
63                tracing::warn!("Failed to ensure {} service: {}", service, e);
64                // Continue with other services
65            }
66        }
67
68        info!("Systemd units installed and started");
69        true
70    })
71}