Explore the GuruRMM agent codebase to understand how the agent handles configuration. Look at:

1. agent/src/config.rs - current configuration structure
2. agent/src/main.rs - how config is loaded/applied
3. agent/src/transport/websocket.rs - how agent communicates with server
4. Any message types for receiving settings from server

I need to understand how the agent currently handles settings so I can design how policies would be received and applied. Report:
- Current config structure and what settings exist
- How agent receives updates from server
- Message protocol patterns used


I'll explore the GuruRMM agent codebase to understand the configuration handling. Let me start by examining the key files you mentioned.


Error: EISDIR: illegal operation on a directory, read


Now let me read the specific files:


     1→//! Agent configuration handling
     2→//!
     3→//! Configuration is loaded from a TOML file (default: agent.toml).
     4→//! The config file defines server connection, metrics collection,
     5→//! and watchdog settings.
     6→
     7→use anyhow::{Context, Result};
     8→use serde::{Deserialize, Serialize};
     9→use std::path::Path;
    10→
    11→/// Root configuration structure
    12→#[derive(Debug, Clone, Serialize, Deserialize)]
    13→pub struct AgentConfig {
    14→    /// Server connection settings
    15→    pub server: ServerConfig,
    16→
    17→    /// Metrics collection settings
    18→    #[serde(default)]
    19→    pub metrics: MetricsConfig,
    20→
    21→    /// Watchdog settings for monitoring services/processes
    22→    #[serde(default)]
    23→    pub watchdog: WatchdogConfig,
    24→}
    25→
    26→/// Server connection configuration
    27→#[derive(Debug, Clone, Serialize, Deserialize)]
    28→pub struct ServerConfig {
    29→    /// WebSocket URL for the GuruRMM server (e.g., wss://rmm.example.com/ws)
    30→    pub url: String,
    31→
    32→    /// API key for authentication (obtained from server during registration)
    33→    pub api_key: String,
    34→
    35→    /// Optional custom hostname to report (defaults to system hostname)
    36→    pub hostname_override: Option<String>,
    37→}
    38→
    39→/// Metrics collection configuration
    40→#[derive(Debug, Clone, Serialize, Deserialize)]
    41→pub struct MetricsConfig {
    42→    /// Interval in seconds between metrics collection (default: 60)
    43→    #[serde(default = "default_metrics_interval")]
    44→    pub interval_seconds: u64,
    45→
    46→    /// Whether to collect CPU metrics
    47→    #[serde(default = "default_true")]
    48→    pub collect_cpu: bool,
    49→
    50→    /// Whether to collect memory metrics
    51→    #[serde(default = "default_true")]
    52→    pub collect_memory: bool,
    53→
    54→    /// Whether to collect disk metrics
    55→    #[serde(default = "default_true")]
    56→    pub collect_disk: bool,
    57→
    58→    /// Whether to collect network metrics
    59→    #[serde(default = "default_true")]
    60→    pub collect_network: bool,
    61→}
    62→
    63→impl Default for MetricsConfig {
    64→    fn default() -> Self {
    65→        Self {
    66→            interval_seconds: 60,
    67→            collect_cpu: true,
    68→            collect_memory: true,
    69→            collect_disk: true,
    70→            collect_network: true,
    71→        }
    72→    }
    73→}
    74→
    75→/// Watchdog configuration for service/process monitoring
    76→#[derive(Debug, Clone, Serialize, Deserialize)]
    77→pub struct WatchdogConfig {
    78→    /// Enable/disable watchdog functionality
    79→    #[serde(default)]
    80→    pub enabled: bool,
    81→
    82→    /// Interval in seconds between watchdog checks (default: 30)
    83→    #[serde(default = "default_watchdog_interval")]
    84→    pub check_interval_seconds: u64,
    85→
    86→    /// List of Windows/systemd services to monitor
    87→    #[serde(default)]
    88→    pub services: Vec<ServiceWatch>,
    89→
    90→    /// List of processes to monitor
    91→    #[serde(default)]
    92→    pub processes: Vec<ProcessWatch>,
    93→}
    94→
    95→impl Default for WatchdogConfig {
    96→    fn default() -> Self {
    97→        Self {
    98→            enabled: false,
    99→            check_interval_seconds: 30,
   100→            services: Vec::new(),
   101→            processes: Vec::new(),
   102→        }
   103→    }
   104→}
   105→
   106→/// Configuration for monitoring a service
   107→#[derive(Debug, Clone, Serialize, Deserialize)]
   108→pub struct ServiceWatch {
   109→    /// Service name (e.g., "CagService" for Datto RMM, "Syncro" for Syncro)
   110→    pub name: String,
   111→
   112→    /// Action to take when service is stopped
   113→    #[serde(default)]
   114→    pub action: WatchAction,
   115→
   116→    /// Maximum number of restart attempts before alerting (default: 3)
   117→    #[serde(default = "default_max_restarts")]
   118→    pub max_restarts: u32,
   119→
   120→    /// Cooldown period in seconds between restart attempts
   121→    #[serde(default = "default_restart_cooldown")]
   122→    pub restart_cooldown_seconds: u64,
   123→}
   124→
   125→/// Configuration for monitoring a process
   126→#[derive(Debug, Clone, Serialize, Deserialize)]
   127→pub struct ProcessWatch {
   128→    /// Process name (e.g., "AEM.exe")
   129→    pub name: String,
   130→
   131→    /// Action to take when process is not found
   132→    #[serde(default)]
   133→    pub action: WatchAction,
   134→
   135→    /// Optional path to executable to start if process is not running
   136→    pub start_command: Option<String>,
   137→}
   138→
   139→/// Action to take when a watched service/process is down
   140→#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
   141→#[serde(rename_all = "lowercase")]
   142→pub enum WatchAction {
   143→    /// Only send an alert to the server
   144→    #[default]
   145→    Alert,
   146→
   147→    /// Attempt to restart the service/process
   148→    Restart,
   149→
   150→    /// Ignore (for temporary disable without removing config)
   151→    Ignore,
   152→}
   153→
   154→// Default value functions for serde
   155→fn default_metrics_interval() -> u64 {
   156→    60
   157→}
   158→
   159→fn default_watchdog_interval() -> u64 {
   160→    30
   161→}
   162→
   163→fn default_max_restarts() -> u32 {
   164→    3
   165→}
   166→
   167→fn default_restart_cooldown() -> u64 {
   168→    60
   169→}
   170→
   171→fn default_true() -> bool {
   172→    true
   173→}
   174→
   175→impl AgentConfig {
   176→    /// Load configuration from a TOML file
   177→    pub fn load(path: &Path) -> Result<Self> {
   178→        let content = std::fs::read_to_string(path)
   179→            .with_context(|| format!("Failed to read config file: {:?}", path))?;
   180→
   181→        let config: Self = toml::from_str(&content)
   182→            .with_context(|| format!("Failed to parse config file: {:?}", path))?;
   183→
   184→        config.validate()?;
   185→        Ok(config)
   186→    }
   187→
   188→    /// Validate the configuration
   189→    fn validate(&self) -> Result<()> {
   190→        // Validate server URL
   191→        if self.server.url.is_empty() {
   192→            anyhow::bail!("Server URL cannot be empty");
   193→        }
   194→
   195→        if !self.server.url.starts_with("ws://") && !self.server.url.starts_with("wss://") {
   196→            anyhow::bail!("Server URL must start with ws:// or wss://");
   197→        }
   198→
   199→        // Validate API key
   200→        if self.server.api_key.is_empty() {
   201→            anyhow::bail!("API key cannot be empty");
   202→        }
   203→
   204→        // Validate intervals
   205→        if self.metrics.interval_seconds < 10 {
   206→            anyhow::bail!("Metrics interval must be at least 10 seconds");
   207→        }
   208→
   209→        if self.watchdog.check_interval_seconds < 5 {
   210→            anyhow::bail!("Watchdog check interval must be at least 5 seconds");
   211→        }
   212→
   213→        Ok(())
   214→    }
   215→
   216→    /// Generate a sample configuration
   217→    pub fn sample() -> Self {
   218→        Self {
   219→            server: ServerConfig {
   220→                url: "wss://rmm-api.azcomputerguru.com/ws".to_string(),
   221→                api_key: "your-api-key-here".to_string(),
   222→                hostname_override: None,
   223→            },
   224→            metrics: MetricsConfig::default(),
   225→            watchdog: WatchdogConfig {
   226→                enabled: true,
   227→                check_interval_seconds: 30,
   228→                services: vec![
   229→                    ServiceWatch {
   230→                        name: "CagService".to_string(), // Datto RMM
   231→                        action: WatchAction::Restart,
   232→                        max_restarts: 3,
   233→                        restart_cooldown_seconds: 60,
   234→                    },
   235→                    ServiceWatch {
   236→                        name: "Syncro".to_string(),
   237→                        action: WatchAction::Restart,
   238→                        max_restarts: 3,
   239→                        restart_cooldown_seconds: 60,
   240→                    },
   241→                ],
   242→                processes: vec![ProcessWatch {
   243→                    name: "AEM.exe".to_string(), // Datto AEM
   244→                    action: WatchAction::Alert,
   245→                    start_command: None,
   246→                }],
   247→            },
   248→        }
   249→    }
   250→
   251→    /// Get the hostname to report to the server
   252→    pub fn get_hostname(&self) -> String {
   253→        self.server
   254→            .hostname_override
   255→            .clone()
   256→            .unwrap_or_else(|| hostname::get().map(|h| h.to_string_lossy().to_string()).unwrap_or_else(|_| "unknown".to_string()))
   257→    }
   258→}
   259→
   260→#[cfg(test)]
   261→mod tests {
   262→    use super::*;
   263→
   264→    #[test]
   265→    fn test_sample_config_is_valid_structure() {
   266→        let sample = AgentConfig::sample();
   267→        // Sample uses placeholder values, so it won't pass full validation
   268→        // but the structure should be correct
   269→        assert!(!sample.server.url.is_empty());
   270→        assert!(!sample.server.api_key.is_empty());
   271→        assert!(sample.watchdog.enabled);
   272→        assert!(!sample.watchdog.services.is_empty());
   273→    }
   274→
   275→    #[test]
   276→    fn test_default_metrics_config() {
   277→        let config = MetricsConfig::default();
   278→        assert_eq!(config.interval_seconds, 60);
   279→        assert!(config.collect_cpu);
   280→        assert!(config.collect_memory);
   281→        assert!(config.collect_disk);
   282→        assert!(config.collect_network);
   283→    }
   284→
   285→    #[test]
   286→    fn test_watch_action_default() {
   287→        let action = WatchAction::default();
   288→        assert_eq!(action, WatchAction::Alert);
   289→    }
   290→}
   291→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

//! Agent configuration handling
//!
//! Configuration is loaded from a TOML file (default: agent.toml).
//! The config file defines server connection, metrics collection,
//! and watchdog settings.

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Root configuration structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    /// Server connection settings
    pub server: ServerConfig,

    /// Metrics collection settings
    #[serde(default)]
    pub metrics: MetricsConfig,

    /// Watchdog settings for monitoring services/processes
    #[serde(default)]
    pub watchdog: WatchdogConfig,
}

/// Server connection configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    /// WebSocket URL for the GuruRMM server (e.g., wss://rmm.example.com/ws)
    pub url: String,

    /// API key for authentication (obtained from server during registration)
    pub api_key: String,

    /// Optional custom hostname to report (defaults to system hostname)
    pub hostname_override: Option<String>,
}

/// Metrics collection configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricsConfig {
    /// Interval in seconds between metrics collection (default: 60)
    #[serde(default = "default_metrics_interval")]
    pub interval_seconds: u64,

    /// Whether to collect CPU metrics
    #[serde(default = "default_true")]
    pub collect_cpu: bool,

    /// Whether to collect memory metrics
    #[serde(default = "default_true")]
    pub collect_memory: bool,

    /// Whether to collect disk metrics
    #[serde(default = "default_true")]
    pub collect_disk: bool,

    /// Whether to collect network metrics
    #[serde(default = "default_true")]
    pub collect_network: bool,
}

impl Default for MetricsConfig {
    fn default() -> Self {
        Self {
            interval_seconds: 60,
            collect_cpu: true,
            collect_memory: true,
            collect_disk: true,
            collect_network: true,
        }
    }
}

/// Watchdog configuration for service/process monitoring
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WatchdogConfig {
    /// Enable/disable watchdog functionality
    #[serde(default)]
    pub enabled: bool,

    /// Interval in seconds between watchdog checks (default: 30)
    #[serde(default = "default_watchdog_interval")]
    pub check_interval_seconds: u64,

    /// List of Windows/systemd services to monitor
    #[serde(default)]
    pub services: Vec<ServiceWatch>,

    /// List of processes to monitor
    #[serde(default)]
    pub processes: Vec<ProcessWatch>,
}

impl Default for WatchdogConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            check_interval_seconds: 30,
            services: Vec::new(),
            processes: Vec::new(),
        }
    }
}

/// Configuration for monitoring a service
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceWatch {
    /// Service name (e.g., "CagService" for Datto RMM, "Syncro" for Syncro)
    pub name: String,

    /// Action to take when service is stopped
    #[serde(default)]
    pub action: WatchAction,

    /// Maximum number of restart attempts before alerting (default: 3)
    #[serde(default = "default_max_restarts")]
    pub max_restarts: u32,

    /// Cooldown period in seconds between restart attempts
    #[serde(default = "default_restart_cooldown")]
    pub restart_cooldown_seconds: u64,
}

/// Configuration for monitoring a process
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessWatch {
    /// Process name (e.g., "AEM.exe")
    pub name: String,

    /// Action to take when process is not found
    #[serde(default)]
    pub action: WatchAction,

    /// Optional path to executable to start if process is not running
    pub start_command: Option<String>,
}

/// Action to take when a watched service/process is down
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum WatchAction {
    /// Only send an alert to the server
    #[default]
    Alert,

    /// Attempt to restart the service/process
    Restart,

    /// Ignore (for temporary disable without removing config)
    Ignore,
}

// Default value functions for serde
fn default_metrics_interval() -> u64 {
    60
}

fn default_watchdog_interval() -> u64 {
    30
}

fn default_max_restarts() -> u32 {
    3
}

fn default_restart_cooldown() -> u64 {
    60
}

fn default_true() -> bool {
    true
}

impl AgentConfig {
    /// Load configuration from a TOML file
    pub fn load(path: &Path) -> Result<Self> {
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read config file: {:?}", path))?;

        let config: Self = toml::from_str(&content)
            .with_context(|| format!("Failed to parse config file: {:?}", path))?;

        config.validate()?;
        Ok(config)
    }

    /// Validate the configuration
    fn validate(&self) -> Result<()> {
        // Validate server URL
        if self.server.url.is_empty() {
            anyhow::bail!("Server URL cannot be empty");
        }

        if !self.server.url.starts_with("ws://") && !self.server.url.starts_with("wss://") {
            anyhow::bail!("Server URL must start with ws:// or wss://");
        }

        // Validate API key
        if self.server.api_key.is_empty() {
            anyhow::bail!("API key cannot be empty");
        }

        // Validate intervals
        if self.metrics.interval_seconds < 10 {
            anyhow::bail!("Metrics interval must be at least 10 seconds");
        }

        if self.watchdog.check_interval_seconds < 5 {
            anyhow::bail!("Watchdog check interval must be at least 5 seconds");
        }

        Ok(())
    }

    /// Generate a sample configuration
    pub fn sample() -> Self {
        Self {
            server: ServerConfig {
                url: "wss://rmm-api.azcomputerguru.com/ws".to_string(),
                api_key: "your-api-key-here".to_string(),
                hostname_override: None,
            },
            metrics: MetricsConfig::default(),
            watchdog: WatchdogConfig {
                enabled: true,
                check_interval_seconds: 30,
                services: vec![
                    ServiceWatch {
                        name: "CagService".to_string(), // Datto RMM
                        action: WatchAction::Restart,
                        max_restarts: 3,
                        restart_cooldown_seconds: 60,
                    },
                    ServiceWatch {
                        name: "Syncro".to_string(),
                        action: WatchAction::Restart,
                        max_restarts: 3,
                        restart_cooldown_seconds: 60,
                    },
                ],
                processes: vec![ProcessWatch {
                    name: "AEM.exe".to_string(), // Datto AEM
                    action: WatchAction::Alert,
                    start_command: None,
                }],
            },
        }
    }

    /// Get the hostname to report to the server
    pub fn get_hostname(&self) -> String {
        self.server
            .hostname_override
            .clone()
            .unwrap_or_else(|| hostname::get().map(|h| h.to_string_lossy().to_string()).unwrap_or_else(|_| "unknown".to_string()))
    }
}

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

    #[test]
    fn test_sample_config_is_valid_structure() {
        let sample = AgentConfig::sample();
        // Sample uses placeholder values, so it won't pass full validation
        // but the structure should be correct
        assert!(!sample.server.url.is_empty());
        assert!(!sample.server.api_key.is_empty());
        assert!(sample.watchdog.enabled);
        assert!(!sample.watchdog.services.is_empty());
    }

    #[test]
    fn test_default_metrics_config() {
        let config = MetricsConfig::default();
        assert_eq!(config.interval_seconds, 60);
        assert!(config.collect_cpu);
        assert!(config.collect_memory);
        assert!(config.collect_disk);
        assert!(config.collect_network);
    }

    #[test]
    fn test_watch_action_default() {
        let action = WatchAction::default();
        assert_eq!(action, WatchAction::Alert);
    }
}


     1→//! GuruRMM Agent - Cross-platform Remote Monitoring and Management Agent
     2→//!
     3→//! This agent connects to the GuruRMM server, reports system metrics,
     4→//! monitors services (watchdog), and executes remote commands.
     5→
     6→mod config;
     7→mod device_id;
     8→mod ipc;
     9→mod metrics;
    10→mod service;
    11→mod transport;
    12→mod tray_launcher;
    13→mod updater;
    14→
    15→use anyhow::{Context, Result};
    16→use clap::{Parser, Subcommand};
    17→use std::path::PathBuf;
    18→use std::sync::Arc;
    19→use tokio::sync::RwLock;
    20→use tracing::{error, info, warn};
    21→
    22→use crate::config::AgentConfig;
    23→use crate::metrics::MetricsCollector;
    24→use crate::transport::WebSocketClient;
    25→
    26→/// GuruRMM Agent - Remote Monitoring and Management
    27→#[derive(Parser)]
    28→#[command(name = "gururmm-agent")]
    29→#[command(author, version, about, long_about = None)]
    30→struct Cli {
    31→    /// Path to configuration file
    32→    #[arg(short, long, default_value = "agent.toml")]
    33→    config: PathBuf,
    34→
    35→    /// Subcommand to run
    36→    #[command(subcommand)]
    37→    command: Option<Commands>,
    38→}
    39→
    40→#[derive(Subcommand)]
    41→enum Commands {
    42→    /// Run the agent (default)
    43→    Run,
    44→
    45→    /// Install as a system service
    46→    Install {
    47→        /// Server WebSocket URL (e.g., wss://rmm-api.example.com/ws)
    48→        #[arg(long)]
    49→        server_url: Option<String>,
    50→
    51→        /// API key for authentication
    52→        #[arg(long)]
    53→        api_key: Option<String>,
    54→
    55→        /// Skip legacy service detection and cleanup
    56→        #[arg(long, default_value = "false")]
    57→        skip_legacy_check: bool,
    58→    },
    59→
    60→    /// Uninstall the system service
    61→    Uninstall,
    62→
    63→    /// Start the installed service
    64→    Start,
    65→
    66→    /// Stop the installed service
    67→    Stop,
    68→
    69→    /// Show agent status
    70→    Status,
    71→
    72→    /// Generate a sample configuration file
    73→    GenerateConfig {
    74→        /// Output path for config file
    75→        #[arg(short, long, default_value = "agent.toml")]
    76→        output: PathBuf,
    77→    },
    78→
    79→    /// Run as Windows service (called by SCM, not for manual use)
    80→    #[command(hide = true)]
    81→    Service,
    82→}
    83→
    84→/// Shared application state
    85→pub struct AppState {
    86→    pub config: AgentConfig,
    87→    pub metrics_collector: MetricsCollector,
    88→    pub connected: RwLock<bool>,
    89→    pub last_checkin: RwLock<Option<chrono::DateTime<chrono::Utc>>>,
    90→    pub tray_policy: RwLock<ipc::TrayPolicy>,
    91→}
    92→
    93→#[tokio::main]
    94→async fn main() -> Result<()> {
    95→    // Initialize logging
    96→    tracing_subscriber::fmt()
    97→        .with_env_filter(
    98→            tracing_subscriber::EnvFilter::from_default_env()
    99→                .add_directive("gururmm_agent=info".parse()?)
   100→                .add_directive("info".parse()?),
   101→        )
   102→        .init();
   103→
   104→    let cli = Cli::parse();
   105→
   106→    match cli.command.unwrap_or(Commands::Run) {
   107→        Commands::Run => run_agent(cli.config).await,
   108→        Commands::Install { server_url, api_key, skip_legacy_check } => {
   109→            install_service(server_url, api_key, skip_legacy_check).await
   110→        }
   111→        Commands::Uninstall => uninstall_service().await,
   112→        Commands::Start => start_service().await,
   113→        Commands::Stop => stop_service().await,
   114→        Commands::Status => show_status(cli.config).await,
   115→        Commands::GenerateConfig { output } => generate_config(output).await,
   116→        Commands::Service => run_as_windows_service(),
   117→    }
   118→}
   119→
   120→/// Run as a Windows service (called by SCM)
   121→fn run_as_windows_service() -> Result<()> {
   122→    #[cfg(windows)]
   123→    {
   124→        service::windows::run_as_service()
   125→    }
   126→
   127→    #[cfg(not(windows))]
   128→    {
   129→        anyhow::bail!("Windows service mode is only available on Windows");
   130→    }
   131→}
   132→
   133→/// Main agent runtime loop
   134→async fn run_agent(config_path: PathBuf) -> Result<()> {
   135→    info!("GuruRMM Agent starting...");
   136→
   137→    // Load configuration
   138→    let config = AgentConfig::load(&config_path)?;
   139→    info!("Loaded configuration from {:?}", config_path);
   140→    info!("Server URL: {}", config.server.url);
   141→
   142→    // Initialize metrics collector
   143→    let metrics_collector = MetricsCollector::new();
   144→    info!("Metrics collector initialized");
   145→
   146→    // Create channels for IPC commands
   147→    let (force_checkin_tx, mut force_checkin_rx) = tokio::sync::mpsc::channel::<()>(8);
   148→    let (stop_agent_tx, mut stop_agent_rx) = tokio::sync::mpsc::channel::<()>(1);
   149→
   150→    // Create shared state
   151→    let state = Arc::new(AppState {
   152→        config: config.clone(),
   153→        metrics_collector,
   154→        connected: RwLock::new(false),
   155→        last_checkin: RwLock::new(None),
   156→        tray_policy: RwLock::new(ipc::TrayPolicy::default_permissive()),
   157→    });
   158→
   159→    // Create IPC state for tray communication
   160→    let device_id = device_id::get_device_id();
   161→    let hostname = hostname::get()
   162→        .map(|h| h.to_string_lossy().to_string())
   163→        .unwrap_or_else(|_| "unknown".to_string());
   164→
   165→    let initial_status = ipc::AgentStatus {
   166→        connected: false,
   167→        last_checkin: None,
   168→        server_url: config.server.url.clone(),
   169→        agent_version: env!("CARGO_PKG_VERSION").to_string(),
   170→        device_id,
   171→        hostname,
   172→        error: None,
   173→    };
   174→
   175→    let ipc_state = Arc::new(ipc::IpcState::new(
   176→        initial_status,
   177→        ipc::TrayPolicy::default_permissive(),
   178→        force_checkin_tx,
   179→        stop_agent_tx,
   180→    ));
   181→
   182→    // Start IPC server for tray application
   183→    let ipc_server_state = Arc::clone(&ipc_state);
   184→    let ipc_handle = tokio::spawn(async move {
   185→        if let Err(e) = ipc::server::run_ipc_server(ipc_server_state).await {
   186→            error!("IPC server error: {}", e);
   187→        }
   188→    });
   189→    info!("IPC server started");
   190→
   191→    // Start tray launcher (Windows only for now)
   192→    #[cfg(windows)]
   193→    let tray_launcher = {
   194→        let tray_exe_path = std::path::PathBuf::from(
   195→            format!("{}\\gururmm-tray.exe", service::windows::INSTALL_DIR)
   196→        );
   197→        let launcher = Arc::new(tray_launcher::TrayLauncher::new(tray_exe_path));
   198→
   199→        // Launch tray in existing sessions
   200→        let launcher_init = Arc::clone(&launcher);
   201→        tokio::spawn(async move {
   202→            // Small delay to let IPC server fully start
   203→            tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
   204→            launcher_init.ensure_running().await;
   205→        });
   206→
   207→        // Periodic check for new sessions (every 30 seconds)
   208→        let launcher_periodic = Arc::clone(&launcher);
   209→        tokio::spawn(async move {
   210→            let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(30));
   211→            loop {
   212→                interval.tick().await;
   213→                launcher_periodic.ensure_running().await;
   214→            }
   215→        });
   216→
   217→        info!("Tray launcher initialized");
   218→        Some(launcher)
   219→    };
   220→
   221→    #[cfg(not(windows))]
   222→    let tray_launcher: Option<Arc<tray_launcher::TrayLauncher>> = None;
   223→
   224→    // Start the WebSocket client with auto-reconnect
   225→    let ws_state = Arc::clone(&state);
   226→    let ws_handle = tokio::spawn(async move {
   227→        loop {
   228→            info!("Connecting to server...");
   229→            match WebSocketClient::connect_and_run(Arc::clone(&ws_state)).await {
   230→                Ok(_) => {
   231→                    warn!("WebSocket connection closed normally, reconnecting...");
   232→                }
   233→                Err(e) => {
   234→                    error!("WebSocket error: {}, reconnecting in 10 seconds...", e);
   235→                }
   236→            }
   237→
   238→            // Mark as disconnected
   239→            *ws_state.connected.write().await = false;
   240→
   241→            // Wait before reconnecting
   242→            tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;
   243→        }
   244→    });
   245→
   246→    // Start metrics collection loop
   247→    let metrics_state = Arc::clone(&state);
   248→    let metrics_handle = tokio::spawn(async move {
   249→        let interval = metrics_state.config.metrics.interval_seconds;
   250→        let mut interval_timer = tokio::time::interval(tokio::time::Duration::from_secs(interval));
   251→
   252→        loop {
   253→            interval_timer.tick().await;
   254→
   255→            // Collect metrics (they'll be sent via WebSocket if connected)
   256→            let metrics = metrics_state.metrics_collector.collect().await;
   257→            if *metrics_state.connected.read().await {
   258→                info!(
   259→                    "Metrics: CPU={:.1}%, Mem={:.1}%, Disk={:.1}%",
   260→                    metrics.cpu_percent, metrics.memory_percent, metrics.disk_percent
   261→                );
   262→            }
   263→        }
   264→    });
   265→
   266→    // Task to update IPC status periodically
   267→    let ipc_update_state = Arc::clone(&state);
   268→    let ipc_update_ipc = Arc::clone(&ipc_state);
   269→    let ipc_update_handle = tokio::spawn(async move {
   270→        let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(5));
   271→        loop {
   272→            interval.tick().await;
   273→
   274→            let connected = *ipc_update_state.connected.read().await;
   275→            let last_checkin = ipc_update_state.last_checkin.read().await.map(|dt| dt.to_rfc3339());
   276→
   277→            let status = ipc::AgentStatus {
   278→                connected,
   279→                last_checkin,
   280→                server_url: ipc_update_state.config.server.url.clone(),
   281→                agent_version: env!("CARGO_PKG_VERSION").to_string(),
   282→                device_id: device_id::get_device_id(),
   283→                hostname: hostname::get()
   284→                    .map(|h| h.to_string_lossy().to_string())
   285→                    .unwrap_or_else(|_| "unknown".to_string()),
   286→                error: if connected { None } else { Some("Disconnected".to_string()) },
   287→            };
   288→
   289→            ipc_update_ipc.update_status(status).await;
   290→        }
   291→    });
   292→
   293→    // Wait for shutdown signal or stop request
   294→    tokio::select! {
   295→        _ = tokio::signal::ctrl_c() => {
   296→            info!("Received shutdown signal");
   297→        }
   298→        _ = stop_agent_rx.recv() => {
   299→            info!("Received stop request from tray");
   300→        }
   301→        _ = ws_handle => {
   302→            error!("WebSocket task ended unexpectedly");
   303→        }
   304→        _ = metrics_handle => {
   305→            error!("Metrics task ended unexpectedly");
   306→        }
   307→        _ = ipc_handle => {
   308→            error!("IPC server ended unexpectedly");
   309→        }
   310→        _ = ipc_update_handle => {
   311→            error!("IPC update task ended unexpectedly");
   312→        }
   313→    }
   314→
   315→    // Terminate tray processes on shutdown
   316→    #[cfg(windows)]
   317→    if let Some(launcher) = tray_launcher {
   318→        info!("Terminating tray processes...");
   319→        launcher.terminate_all().await;
   320→    }
   321→
   322→    #[cfg(not(windows))]
   323→    let _ = tray_launcher; // Suppress unused warning
   324→
   325→    info!("GuruRMM Agent shutting down");
   326→    Ok(())
   327→}
   328→
   329→/// Install the agent as a system service
   330→async fn install_service(
   331→    server_url: Option<String>,
   332→    api_key: Option<String>,
   333→    skip_legacy_check: bool,
   334→) -> Result<()> {
   335→    #[cfg(windows)]
   336→    {
   337→        service::windows::install(server_url, api_key, skip_legacy_check)
   338→    }
   339→
   340→    #[cfg(target_os = "linux")]
   341→    {
   342→        install_systemd_service(server_url, api_key, skip_legacy_check).await
   343→    }
   344→
   345→    #[cfg(target_os = "macos")]
   346→    {
   347→        let _ = (server_url, api_key, skip_legacy_check); // Suppress unused warnings
   348→        info!("Installing GuruRMM Agent as launchd service...");
   349→        todo!("macOS launchd service installation not yet implemented");
   350→    }
   351→}
   352→
   353→/// Legacy service names to check for and clean up (Linux)
   354→#[cfg(target_os = "linux")]
   355→const LINUX_LEGACY_SERVICE_NAMES: &[&str] = &[
   356→    "gururmm",           // Old name without -agent suffix
   357→    "guru-rmm-agent",    // Alternative naming
   358→    "GuruRMM-Agent",     // Case variant
   359→];
   360→
   361→/// Clean up legacy Linux service installations
   362→#[cfg(target_os = "linux")]
   363→fn cleanup_legacy_linux_services() -> Result<()> {
   364→    use std::process::Command;
   365→
   366→    info!("Checking for legacy service installations...");
   367→
   368→    for legacy_name in LINUX_LEGACY_SERVICE_NAMES {
   369→        // Check if service exists
   370→        let status = Command::new("systemctl")
   371→            .args(["status", legacy_name])
   372→            .output();
   373→
   374→        if let Ok(output) = status {
   375→            if output.status.success() || String::from_utf8_lossy(&output.stderr).contains("Loaded:") {
   376→                info!("Found legacy service '{}', removing...", legacy_name);
   377→
   378→                // Stop the service
   379→                let _ = Command::new("systemctl")
   380→                    .args(["stop", legacy_name])
   381→                    .status();
   382→
   383→                // Disable the service
   384→                let _ = Command::new("systemctl")
   385→                    .args(["disable", legacy_name])
   386→                    .status();
   387→
   388→                // Remove unit file
   389→                let unit_file = format!("/etc/systemd/system/{}.service", legacy_name);
   390→                if std::path::Path::new(&unit_file).exists() {
   391→                    info!("Removing legacy unit file: {}", unit_file);
   392→                    let _ = std::fs::remove_file(&unit_file);
   393→                }
   394→            }
   395→        }
   396→    }
   397→
   398→    // Check for legacy binaries in common locations
   399→    let legacy_binary_locations = [
   400→        "/usr/local/bin/gururmm",
   401→        "/usr/bin/gururmm",
   402→        "/opt/gururmm/gururmm",
   403→        "/opt/gururmm/agent",
   404→    ];
   405→
   406→    for legacy_path in legacy_binary_locations {
   407→        if std::path::Path::new(legacy_path).exists() {
   408→            info!("Found legacy binary at '{}', removing...", legacy_path);
   409→            let _ = std::fs::remove_file(legacy_path);
   410→        }
   411→    }
   412→
   413→    // Reload systemd to pick up removed unit files
   414→    let _ = Command::new("systemctl")
   415→        .args(["daemon-reload"])
   416→        .status();
   417→
   418→    Ok(())
   419→}
   420→
   421→/// Install as a systemd service (Linux)
   422→#[cfg(target_os = "linux")]
   423→async fn install_systemd_service(
   424→    server_url: Option<String>,
   425→    api_key: Option<String>,
   426→    skip_legacy_check: bool,
   427→) -> Result<()> {
   428→    use std::process::Command;
   429→
   430→    const SERVICE_NAME: &str = "gururmm-agent";
   431→    const INSTALL_DIR: &str = "/usr/local/bin";
   432→    const CONFIG_DIR: &str = "/etc/gururmm";
   433→    const SYSTEMD_DIR: &str = "/etc/systemd/system";
   434→
   435→    info!("Installing GuruRMM Agent as systemd service...");
   436→
   437→    // Check if running as root
   438→    if !nix::unistd::geteuid().is_root() {
   439→        anyhow::bail!("Installation requires root privileges. Please run with sudo.");
   440→    }
   441→
   442→    // Clean up legacy installations unless skipped
   443→    if !skip_legacy_check {
   444→        if let Err(e) = cleanup_legacy_linux_services() {
   445→            warn!("Legacy cleanup warning: {}", e);
   446→        }
   447→    }
   448→
   449→    // Get the current executable path
   450→    let current_exe = std::env::current_exe()
   451→        .context("Failed to get current executable path")?;
   452→
   453→    let binary_dest = format!("{}/{}", INSTALL_DIR, SERVICE_NAME);
   454→    let config_dest = format!("{}/agent.toml", CONFIG_DIR);
   455→    let unit_file = format!("{}/{}.service", SYSTEMD_DIR, SERVICE_NAME);
   456→
   457→    // Create config directory
   458→    info!("Creating config directory: {}", CONFIG_DIR);
   459→    std::fs::create_dir_all(CONFIG_DIR)
   460→        .context("Failed to create config directory")?;
   461→
   462→    // Copy binary
   463→    info!("Copying binary to: {}", binary_dest);
   464→    std::fs::copy(&current_exe, &binary_dest)
   465→        .context("Failed to copy binary")?;
   466→
   467→    // Make binary executable
   468→    Command::new("chmod")
   469→        .args(["+x", &binary_dest])
   470→        .status()
   471→        .context("Failed to set binary permissions")?;
   472→
   473→    // Handle configuration
   474→    let config_needs_manual_edit;
   475→    if !std::path::Path::new(&config_dest).exists() {
   476→        info!("Creating config: {}", config_dest);
   477→
   478→        // Start with sample config
   479→        let mut config = crate::config::AgentConfig::sample();
   480→
   481→        // Apply provided values
   482→        if let Some(url) = &server_url {
   483→            config.server.url = url.clone();
   484→        }
   485→        if let Some(key) = &api_key {
   486→            config.server.api_key = key.clone();
   487→        }
   488→
   489→        let toml_str = toml::to_string_pretty(&config)?;
   490→        std::fs::write(&config_dest, toml_str)
   491→            .context("Failed to write config file")?;
   492→
   493→        // Set restrictive permissions on config (contains API key)
   494→        Command::new("chmod")
   495→            .args(["600", &config_dest])
   496→            .status()
   497→            .context("Failed to set config permissions")?;
   498→
   499→        config_needs_manual_edit = server_url.is_none() || api_key.is_none();
   500→    } else {
   501→        info!("Config already exists: {}", config_dest);
   502→        config_needs_manual_edit = false;
   503→
   504→        // If server_url or api_key provided, update existing config
   505→        if server_url.is_some() || api_key.is_some() {
   506→            info!("Updating existing configuration...");
   507→            let config_content = std::fs::read_to_string(&config_dest)?;
   508→            let mut config: crate::config::AgentConfig = toml::from_str(&config_content)
   509→                .context("Failed to parse existing config")?;
   510→
   511→            if let Some(url) = &server_url {
   512→                config.server.url = url.clone();
   513→            }
   514→            if let Some(key) = &api_key {
   515→                config.server.api_key = key.clone();
   516→            }
   517→
   518→            let toml_str = toml::to_string_pretty(&config)?;
   519→            std::fs::write(&config_dest, toml_str)
   520→                .context("Failed to update config file")?;
   521→        }
   522→    }
   523→
   524→    // Create systemd unit file
   525→    let unit_content = format!(r#"[Unit]
   526→Description=GuruRMM Agent - Remote Monitoring and Management
   527→Documentation=https://github.com/azcomputerguru/gururmm
   528→After=network-online.target
   529→Wants=network-online.target
   530→
   531→[Service]
   532→Type=simple
   533→ExecStart={binary} --config {config} run
   534→Restart=always
   535→RestartSec=10
   536→StandardOutput=journal
   537→StandardError=journal
   538→SyslogIdentifier={service}
   539→
   540→# Security hardening
   541→NoNewPrivileges=true
   542→ProtectSystem=strict
   543→ProtectHome=read-only
   544→PrivateTmp=true
   545→ReadWritePaths=/var/log
   546→
   547→[Install]
   548→WantedBy=multi-user.target
   549→"#,
   550→        binary = binary_dest,
   551→        config = config_dest,
   552→        service = SERVICE_NAME
   553→    );
   554→
   555→    info!("Creating systemd unit file: {}", unit_file);
   556→    std::fs::write(&unit_file, unit_content)
   557→        .context("Failed to write systemd unit file")?;
   558→
   559→    // Reload systemd daemon
   560→    info!("Reloading systemd daemon...");
   561→    let status = Command::new("systemctl")
   562→        .args(["daemon-reload"])
   563→        .status()
   564→        .context("Failed to reload systemd")?;
   565→
   566→    if !status.success() {
   567→        anyhow::bail!("systemctl daemon-reload failed");
   568→    }
   569→
   570→    // Enable the service
   571→    info!("Enabling service...");
   572→    let status = Command::new("systemctl")
   573→        .args(["enable", SERVICE_NAME])
   574→        .status()
   575→        .context("Failed to enable service")?;
   576→
   577→    if !status.success() {
   578→        anyhow::bail!("systemctl enable failed");
   579→    }
   580→
   581→    println!("\n✓ GuruRMM Agent installed successfully!");
   582→    println!("\nInstalled files:");
   583→    println!("  Binary: {}", binary_dest);
   584→    println!("  Config: {}", config_dest);
   585→    println!("  Service: {}", unit_file);
   586→
   587→    if config_needs_manual_edit {
   588→        println!("\n⚠  IMPORTANT: Edit {} with your server URL and API key!", config_dest);
   589→        println!("\nNext steps:");
   590→        println!("  1. Edit {} with your server URL and API key", config_dest);
   591→        println!("  2. Start the service: sudo systemctl start {}", SERVICE_NAME);
   592→    } else {
   593→        println!("\nStarting service...");
   594→        let status = Command::new("systemctl")
   595→            .args(["start", SERVICE_NAME])
   596→            .status();
   597→
   598→        if status.is_ok() && status.unwrap().success() {
   599→            println!("✓ Service started successfully!");
   600→        } else {
   601→            println!("⚠  Failed to start service. Check logs: sudo journalctl -u {} -f", SERVICE_NAME);
   602→        }
   603→    }
   604→
   605→    println!("\nUseful commands:");
   606→    println!("  Status: sudo systemctl status {}", SERVICE_NAME);
   607→    println!("  Logs:   sudo journalctl -u {} -f", SERVICE_NAME);
   608→    println!("  Stop:   sudo systemctl stop {}", SERVICE_NAME);
   609→    println!("  Start:  sudo systemctl start {}", SERVICE_NAME);
   610→
   611→    Ok(())
   612→}
   613→
   614→/// Uninstall the system service
   615→async fn uninstall_service() -> Result<()> {
   616→    #[cfg(windows)]
   617→    {
   618→        service::windows::uninstall()
   619→    }
   620→
   621→    #[cfg(target_os = "linux")]
   622→    {
   623→        uninstall_systemd_service().await
   624→    }
   625→
   626→    #[cfg(target_os = "macos")]
   627→    {
   628→        todo!("macOS service uninstallation not yet implemented");
   629→    }
   630→}
   631→
   632→/// Uninstall systemd service (Linux)
   633→#[cfg(target_os = "linux")]
   634→async fn uninstall_systemd_service() -> Result<()> {
   635→    use std::process::Command;
   636→
   637→    const SERVICE_NAME: &str = "gururmm-agent";
   638→    const INSTALL_DIR: &str = "/usr/local/bin";
   639→    const CONFIG_DIR: &str = "/etc/gururmm";
   640→    const SYSTEMD_DIR: &str = "/etc/systemd/system";
   641→
   642→    info!("Uninstalling GuruRMM Agent...");
   643→
   644→    if !nix::unistd::geteuid().is_root() {
   645→        anyhow::bail!("Uninstallation requires root privileges. Please run with sudo.");
   646→    }
   647→
   648→    let binary_path = format!("{}/{}", INSTALL_DIR, SERVICE_NAME);
   649→    let unit_file = format!("{}/{}.service", SYSTEMD_DIR, SERVICE_NAME);
   650→
   651→    // Stop the service if running
   652→    info!("Stopping service...");
   653→    let _ = Command::new("systemctl")
   654→        .args(["stop", SERVICE_NAME])
   655→        .status();
   656→
   657→    // Disable the service
   658→    info!("Disabling service...");
   659→    let _ = Command::new("systemctl")
   660→        .args(["disable", SERVICE_NAME])
   661→        .status();
   662→
   663→    // Remove unit file
   664→    if std::path::Path::new(&unit_file).exists() {
   665→        info!("Removing unit file: {}", unit_file);
   666→        std::fs::remove_file(&unit_file)?;
   667→    }
   668→
   669→    // Remove binary
   670→    if std::path::Path::new(&binary_path).exists() {
   671→        info!("Removing binary: {}", binary_path);
   672→        std::fs::remove_file(&binary_path)?;
   673→    }
   674→
   675→    // Reload systemd
   676→    let _ = Command::new("systemctl")
   677→        .args(["daemon-reload"])
   678→        .status();
   679→
   680→    println!("\n✓ GuruRMM Agent uninstalled successfully!");
   681→    println!("\nNote: Config directory {} was preserved.", CONFIG_DIR);
   682→    println!("Remove it manually if no longer needed: sudo rm -rf {}", CONFIG_DIR);
   683→
   684→    Ok(())
   685→}
   686→
   687→/// Start the installed service
   688→async fn start_service() -> Result<()> {
   689→    #[cfg(windows)]
   690→    {
   691→        service::windows::start()
   692→    }
   693→
   694→    #[cfg(target_os = "linux")]
   695→    {
   696→        use std::process::Command;
   697→
   698→        info!("Starting GuruRMM Agent service...");
   699→
   700→        let status = Command::new("systemctl")
   701→            .args(["start", "gururmm-agent"])
   702→            .status()
   703→            .context("Failed to start service")?;
   704→
   705→        if status.success() {
   706→            println!("** Service started successfully");
   707→            println!("Check status: sudo systemctl status gururmm-agent");
   708→        } else {
   709→            anyhow::bail!("Failed to start service. Check: sudo journalctl -u gururmm-agent -n 50");
   710→        }
   711→
   712→        Ok(())
   713→    }
   714→
   715→    #[cfg(target_os = "macos")]
   716→    {
   717→        todo!("macOS service start not yet implemented");
   718→    }
   719→}
   720→
   721→/// Stop the installed service
   722→async fn stop_service() -> Result<()> {
   723→    #[cfg(windows)]
   724→    {
   725→        service::windows::stop()
   726→    }
   727→
   728→    #[cfg(target_os = "linux")]
   729→    {
   730→        use std::process::Command;
   731→
   732→        info!("Stopping GuruRMM Agent service...");
   733→
   734→        let status = Command::new("systemctl")
   735→            .args(["stop", "gururmm-agent"])
   736→            .status()
   737→            .context("Failed to stop service")?;
   738→
   739→        if status.success() {
   740→            println!("** Service stopped successfully");
   741→        } else {
   742→            anyhow::bail!("Failed to stop service");
   743→        }
   744→
   745→        Ok(())
   746→    }
   747→
   748→    #[cfg(target_os = "macos")]
   749→    {
   750→        todo!("macOS service stop not yet implemented");
   751→    }
   752→}
   753→
   754→/// Show agent status
   755→async fn show_status(config_path: PathBuf) -> Result<()> {
   756→    // On Windows, show service status
   757→    #[cfg(windows)]
   758→    {
   759→        service::windows::status()?;
   760→        println!();
   761→    }
   762→
   763→    // Try to load config for additional info
   764→    match AgentConfig::load(&config_path) {
   765→        Ok(config) => {
   766→            println!("Configuration");
   767→            println!("=============");
   768→            println!("Config file: {:?}", config_path);
   769→            println!("Server URL: {}", config.server.url);
   770→            println!("Metrics interval: {} seconds", config.metrics.interval_seconds);
   771→            println!("Watchdog enabled: {}", config.watchdog.enabled);
   772→
   773→            // Collect current metrics
   774→            let collector = MetricsCollector::new();
   775→            let metrics = collector.collect().await;
   776→
   777→            println!("\nCurrent System Metrics:");
   778→            println!("  CPU Usage: {:.1}%", metrics.cpu_percent);
   779→            println!("  Memory Usage: {:.1}%", metrics.memory_percent);
   780→            println!(
   781→                "  Memory Used: {:.2} GB",
   782→                metrics.memory_used_bytes as f64 / 1_073_741_824.0
   783→            );
   784→            println!("  Disk Usage: {:.1}%", metrics.disk_percent);
   785→            println!(
   786→                "  Disk Used: {:.2} GB",
   787→                metrics.disk_used_bytes as f64 / 1_073_741_824.0
   788→            );
   789→        }
   790→        Err(_) => {
   791→            println!("\nConfig file {:?} not found or invalid.", config_path);
   792→            #[cfg(windows)]
   793→            println!("Service config location: {}\\agent.toml", service::windows::CONFIG_DIR);
   794→        }
   795→    }
   796→
   797→    Ok(())
   798→}
   799→
   800→/// Generate a sample configuration file
   801→async fn generate_config(output: PathBuf) -> Result<()> {
   802→    let sample_config = AgentConfig::sample();
   803→    let toml_str = toml::to_string_pretty(&sample_config)?;
   804→
   805→    std::fs::write(&output, toml_str)?;
   806→    println!("Sample configuration written to {:?}", output);
   807→    println!("\nEdit this file with your server URL and API key, then run:");
   808→    println!("  gururmm-agent --config {:?} run", output);
   809→
   810→    Ok(())
   811→}
   812→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

//! GuruRMM Agent - Cross-platform Remote Monitoring and Management Agent
//!
//! This agent connects to the GuruRMM server, reports system metrics,
//! monitors services (watchdog), and executes remote commands.

mod config;
mod device_id;
mod ipc;
mod metrics;
mod service;
mod transport;
mod tray_launcher;
mod updater;

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{error, info, warn};

use crate::config::AgentConfig;
use crate::metrics::MetricsCollector;
use crate::transport::WebSocketClient;

/// GuruRMM Agent - Remote Monitoring and Management
#[derive(Parser)]
#[command(name = "gururmm-agent")]
#[command(author, version, about, long_about = None)]
struct Cli {
    /// Path to configuration file
    #[arg(short, long, default_value = "agent.toml")]
    config: PathBuf,

    /// Subcommand to run
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Run the agent (default)
    Run,

    /// Install as a system service
    Install {
        /// Server WebSocket URL (e.g., wss://rmm-api.example.com/ws)
        #[arg(long)]
        server_url: Option<String>,

        /// API key for authentication
        #[arg(long)]
        api_key: Option<String>,

        /// Skip legacy service detection and cleanup
        #[arg(long, default_value = "false")]
        skip_legacy_check: bool,
    },

    /// Uninstall the system service
    Uninstall,

    /// Start the installed service
    Start,

    /// Stop the installed service
    Stop,

    /// Show agent status
    Status,

    /// Generate a sample configuration file
    GenerateConfig {
        /// Output path for config file
        #[arg(short, long, default_value = "agent.toml")]
        output: PathBuf,
    },

    /// Run as Windows service (called by SCM, not for manual use)
    #[command(hide = true)]
    Service,
}

/// Shared application state
pub struct AppState {
    pub config: AgentConfig,
    pub metrics_collector: MetricsCollector,
    pub connected: RwLock<bool>,
    pub last_checkin: RwLock<Option<chrono::DateTime<chrono::Utc>>>,
    pub tray_policy: RwLock<ipc::TrayPolicy>,
}

#[tokio::main]
async fn main() -> Result<()> {
    // Initialize logging
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::from_default_env()
                .add_directive("gururmm_agent=info".parse()?)
                .add_directive("info".parse()?),
        )
        .init();

    let cli = Cli::parse();

    match cli.command.unwrap_or(Commands::Run) {
        Commands::Run => run_agent(cli.config).await,
        Commands::Install { server_url, api_key, skip_legacy_check } => {
            install_service(server_url, api_key, skip_legacy_check).await
        }
        Commands::Uninstall => uninstall_service().await,
        Commands::Start => start_service().await,
        Commands::Stop => stop_service().await,
        Commands::Status => show_status(cli.config).await,
        Commands::GenerateConfig { output } => generate_config(output).await,
        Commands::Service => run_as_windows_service(),
    }
}

/// Run as a Windows service (called by SCM)
fn run_as_windows_service() -> Result<()> {
    #[cfg(windows)]
    {
        service::windows::run_as_service()
    }

    #[cfg(not(windows))]
    {
        anyhow::bail!("Windows service mode is only available on Windows");
    }
}

/// Main agent runtime loop
async fn run_agent(config_path: PathBuf) -> Result<()> {
    info!("GuruRMM Agent starting...");

    // Load configuration
    let config = AgentConfig::load(&config_path)?;
    info!("Loaded configuration from {:?}", config_path);
    info!("Server URL: {}", config.server.url);

    // Initialize metrics collector
    let metrics_collector = MetricsCollector::new();
    info!("Metrics collector initialized");

    // Create channels for IPC commands
    let (force_checkin_tx, mut force_checkin_rx) = tokio::sync::mpsc::channel::<()>(8);
    let (stop_agent_tx, mut stop_agent_rx) = tokio::sync::mpsc::channel::<()>(1);

    // Create shared state
    let state = Arc::new(AppState {
        config: config.clone(),
        metrics_collector,
        connected: RwLock::new(false),
        last_checkin: RwLock::new(None),
        tray_policy: RwLock::new(ipc::TrayPolicy::default_permissive()),
    });

    // Create IPC state for tray communication
    let device_id = device_id::get_device_id();
    let hostname = hostname::get()
        .map(|h| h.to_string_lossy().to_string())
        .unwrap_or_else(|_| "unknown".to_string());

    let initial_status = ipc::AgentStatus {
        connected: false,
        last_checkin: None,
        server_url: config.server.url.clone(),
        agent_version: env!("CARGO_PKG_VERSION").to_string(),
        device_id,
        hostname,
        error: None,
    };

    let ipc_state = Arc::new(ipc::IpcState::new(
        initial_status,
        ipc::TrayPolicy::default_permissive(),
        force_checkin_tx,
        stop_agent_tx,
    ));

    // Start IPC server for tray application
    let ipc_server_state = Arc::clone(&ipc_state);
    let ipc_handle = tokio::spawn(async move {
        if let Err(e) = ipc::server::run_ipc_server(ipc_server_state).await {
            error!("IPC server error: {}", e);
        }
    });
    info!("IPC server started");

    // Start tray launcher (Windows only for now)
    #[cfg(windows)]
    let tray_launcher = {
        let tray_exe_path = std::path::PathBuf::from(
            format!("{}\\gururmm-tray.exe", service::windows::INSTALL_DIR)
        );
        let launcher = Arc::new(tray_launcher::TrayLauncher::new(tray_exe_path));

        // Launch tray in existing sessions
        let launcher_init = Arc::clone(&launcher);
        tokio::spawn(async move {
            // Small delay to let IPC server fully start
            tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
            launcher_init.ensure_running().await;
        });

        // Periodic check for new sessions (every 30 seconds)
        let launcher_periodic = Arc::clone(&launcher);
        tokio::spawn(async move {
            let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(30));
            loop {
                interval.tick().await;
                launcher_periodic.ensure_running().await;
            }
        });

        info!("Tray launcher initialized");
        Some(launcher)
    };

    #[cfg(not(windows))]
    let tray_launcher: Option<Arc<tray_launcher::TrayLauncher>> = None;

    // Start the WebSocket client with auto-reconnect
    let ws_state = Arc::clone(&state);
    let ws_handle = tokio::spawn(async move {
        loop {
            info!("Connecting to server...");
            match WebSocketClient::connect_and_run(Arc::clone(&ws_state)).await {
                Ok(_) => {
                    warn!("WebSocket connection closed normally, reconnecting...");
                }
                Err(e) => {
                    error!("WebSocket error: {}, reconnecting in 10 seconds...", e);
                }
            }

            // Mark as disconnected
            *ws_state.connected.write().await = false;

            // Wait before reconnecting
            tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;
        }
    });

    // Start metrics collection loop
    let metrics_state = Arc::clone(&state);
    let metrics_handle = tokio::spawn(async move {
        let interval = metrics_state.config.metrics.interval_seconds;
        let mut interval_timer = tokio::time::interval(tokio::time::Duration::from_secs(interval));

        loop {
            interval_timer.tick().await;

            // Collect metrics (they'll be sent via WebSocket if connected)
            let metrics = metrics_state.metrics_collector.collect().await;
            if *metrics_state.connected.read().await {
                info!(
                    "Metrics: CPU={:.1}%, Mem={:.1}%, Disk={:.1}%",
                    metrics.cpu_percent, metrics.memory_percent, metrics.disk_percent
                );
            }
        }
    });

    // Task to update IPC status periodically
    let ipc_update_state = Arc::clone(&state);
    let ipc_update_ipc = Arc::clone(&ipc_state);
    let ipc_update_handle = tokio::spawn(async move {
        let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(5));
        loop {
            interval.tick().await;

            let connected = *ipc_update_state.connected.read().await;
            let last_checkin = ipc_update_state.last_checkin.read().await.map(|dt| dt.to_rfc3339());

            let status = ipc::AgentStatus {
                connected,
                last_checkin,
                server_url: ipc_update_state.config.server.url.clone(),
                agent_version: env!("CARGO_PKG_VERSION").to_string(),
                device_id: device_id::get_device_id(),
                hostname: hostname::get()
                    .map(|h| h.to_string_lossy().to_string())
                    .unwrap_or_else(|_| "unknown".to_string()),
                error: if connected { None } else { Some("Disconnected".to_string()) },
            };

            ipc_update_ipc.update_status(status).await;
        }
    });

    // Wait for shutdown signal or stop request
    tokio::select! {
        _ = tokio::signal::ctrl_c() => {
            info!("Received shutdown signal");
        }
        _ = stop_agent_rx.recv() => {
            info!("Received stop request from tray");
        }
        _ = ws_handle => {
            error!("WebSocket task ended unexpectedly");
        }
        _ = metrics_handle => {
            error!("Metrics task ended unexpectedly");
        }
        _ = ipc_handle => {
            error!("IPC server ended unexpectedly");
        }
        _ = ipc_update_handle => {
            error!("IPC update task ended unexpectedly");
        }
    }

    // Terminate tray processes on shutdown
    #[cfg(windows)]
    if let Some(launcher) = tray_launcher {
        info!("Terminating tray processes...");
        launcher.terminate_all().await;
    }

    #[cfg(not(windows))]
    let _ = tray_launcher; // Suppress unused warning

    info!("GuruRMM Agent shutting down");
    Ok(())
}

/// Install the agent as a system service
async fn install_service(
    server_url: Option<String>,
    api_key: Option<String>,
    skip_legacy_check: bool,
) -> Result<()> {
    #[cfg(windows)]
    {
        service::windows::install(server_url, api_key, skip_legacy_check)
    }

    #[cfg(target_os = "linux")]
    {
        install_systemd_service(server_url, api_key, skip_legacy_check).await
    }

    #[cfg(target_os = "macos")]
    {
        let _ = (server_url, api_key, skip_legacy_check); // Suppress unused warnings
        info!("Installing GuruRMM Agent as launchd service...");
        todo!("macOS launchd service installation not yet implemented");
    }
}

/// Legacy service names to check for and clean up (Linux)
#[cfg(target_os = "linux")]
const LINUX_LEGACY_SERVICE_NAMES: &[&str] = &[
    "gururmm",           // Old name without -agent suffix
    "guru-rmm-agent",    // Alternative naming
    "GuruRMM-Agent",     // Case variant
];

/// Clean up legacy Linux service installations
#[cfg(target_os = "linux")]
fn cleanup_legacy_linux_services() -> Result<()> {
    use std::process::Command;

    info!("Checking for legacy service installations...");

    for legacy_name in LINUX_LEGACY_SERVICE_NAMES {
        // Check if service exists
        let status = Command::new("systemctl")
            .args(["status", legacy_name])
            .output();

        if let Ok(output) = status {
            if output.status.success() || String::from_utf8_lossy(&output.stderr).contains("Loaded:") {
                info!("Found legacy service '{}', removing...", legacy_name);

                // Stop the service
                let _ = Command::new("systemctl")
                    .args(["stop", legacy_name])
                    .status();

                // Disable the service
                let _ = Command::new("systemctl")
                    .args(["disable", legacy_name])
                    .status();

                // Remove unit file
                let unit_file = format!("/etc/systemd/system/{}.service", legacy_name);
                if std::path::Path::new(&unit_file).exists() {
                    info!("Removing legacy unit file: {}", unit_file);
                    let _ = std::fs::remove_file(&unit_file);
                }
            }
        }
    }

    // Check for legacy binaries in common locations
    let legacy_binary_locations = [
        "/usr/local/bin/gururmm",
        "/usr/bin/gururmm",
        "/opt/gururmm/gururmm",
        "/opt/gururmm/agent",
    ];

    for legacy_path in legacy_binary_locations {
        if std::path::Path::new(legacy_path).exists() {
            info!("Found legacy binary at '{}', removing...", legacy_path);
            let _ = std::fs::remove_file(legacy_path);
        }
    }

    // Reload systemd to pick up removed unit files
    let _ = Command::new("systemctl")
        .args(["daemon-reload"])
        .status();

    Ok(())
}

/// Install as a systemd service (Linux)
#[cfg(target_os = "linux")]
async fn install_systemd_service(
    server_url: Option<String>,
    api_key: Option<String>,
    skip_legacy_check: bool,
) -> Result<()> {
    use std::process::Command;

    const SERVICE_NAME: &str = "gururmm-agent";
    const INSTALL_DIR: &str = "/usr/local/bin";
    const CONFIG_DIR: &str = "/etc/gururmm";
    const SYSTEMD_DIR: &str = "/etc/systemd/system";

    info!("Installing GuruRMM Agent as systemd service...");

    // Check if running as root
    if !nix::unistd::geteuid().is_root() {
        anyhow::bail!("Installation requires root privileges. Please run with sudo.");
    }

    // Clean up legacy installations unless skipped
    if !skip_legacy_check {
        if let Err(e) = cleanup_legacy_linux_services() {
            warn!("Legacy cleanup warning: {}", e);
        }
    }

    // Get the current executable path
    let current_exe = std::env::current_exe()
        .context("Failed to get current executable path")?;

    let binary_dest = format!("{}/{}", INSTALL_DIR, SERVICE_NAME);
    let config_dest = format!("{}/agent.toml", CONFIG_DIR);
    let unit_file = format!("{}/{}.service", SYSTEMD_DIR, SERVICE_NAME);

    // Create config directory
    info!("Creating config directory: {}", CONFIG_DIR);
    std::fs::create_dir_all(CONFIG_DIR)
        .context("Failed to create config directory")?;

    // Copy binary
    info!("Copying binary to: {}", binary_dest);
    std::fs::copy(&current_exe, &binary_dest)
        .context("Failed to copy binary")?;

    // Make binary executable
    Command::new("chmod")
        .args(["+x", &binary_dest])
        .status()
        .context("Failed to set binary permissions")?;

    // Handle configuration
    let config_needs_manual_edit;
    if !std::path::Path::new(&config_dest).exists() {
        info!("Creating config: {}", config_dest);

        // Start with sample config
        let mut config = crate::config::AgentConfig::sample();

        // Apply provided values
        if let Some(url) = &server_url {
            config.server.url = url.clone();
        }
        if let Some(key) = &api_key {
            config.server.api_key = key.clone();
        }

        let toml_str = toml::to_string_pretty(&config)?;
        std::fs::write(&config_dest, toml_str)
            .context("Failed to write config file")?;

        // Set restrictive permissions on config (contains API key)
        Command::new("chmod")
            .args(["600", &config_dest])
            .status()
            .context("Failed to set config permissions")?;

        config_needs_manual_edit = server_url.is_none() || api_key.is_none();
    } else {
        info!("Config already exists: {}", config_dest);
        config_needs_manual_edit = false;

        // If server_url or api_key provided, update existing config
        if server_url.is_some() || api_key.is_some() {
            info!("Updating existing configuration...");
            let config_content = std::fs::read_to_string(&config_dest)?;
            let mut config: crate::config::AgentConfig = toml::from_str(&config_content)
                .context("Failed to parse existing config")?;

            if let Some(url) = &server_url {
                config.server.url = url.clone();
            }
            if let Some(key) = &api_key {
                config.server.api_key = key.clone();
            }

            let toml_str = toml::to_string_pretty(&config)?;
            std::fs::write(&config_dest, toml_str)
                .context("Failed to update config file")?;
        }
    }

    // Create systemd unit file
    let unit_content = format!(r#"[Unit]
Description=GuruRMM Agent - Remote Monitoring and Management
Documentation=https://github.com/azcomputerguru/gururmm
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart={binary} --config {config} run
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier={service}

# Security hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=read-only
PrivateTmp=true
ReadWritePaths=/var/log

[Install]
WantedBy=multi-user.target
"#,
        binary = binary_dest,
        config = config_dest,
        service = SERVICE_NAME
    );

    info!("Creating systemd unit file: {}", unit_file);
    std::fs::write(&unit_file, unit_content)
        .context("Failed to write systemd unit file")?;

    // Reload systemd daemon
    info!("Reloading systemd daemon...");
    let status = Command::new("systemctl")
        .args(["daemon-reload"])
        .status()
        .context("Failed to reload systemd")?;

    if !status.success() {
        anyhow::bail!("systemctl daemon-reload failed");
    }

    // Enable the service
    info!("Enabling service...");
    let status = Command::new("systemctl")
        .args(["enable", SERVICE_NAME])
        .status()
        .context("Failed to enable service")?;

    if !status.success() {
        anyhow::bail!("systemctl enable failed");
    }

    println!("\n✓ GuruRMM Agent installed successfully!");
    println!("\nInstalled files:");
    println!("  Binary: {}", binary_dest);
    println!("  Config: {}", config_dest);
    println!("  Service: {}", unit_file);

    if config_needs_manual_edit {
        println!("\n⚠  IMPORTANT: Edit {} with your server URL and API key!", config_dest);
        println!("\nNext steps:");
        println!("  1. Edit {} with your server URL and API key", config_dest);
        println!("  2. Start the service: sudo systemctl start {}", SERVICE_NAME);
    } else {
        println!("\nStarting service...");
        let status = Command::new("systemctl")
            .args(["start", SERVICE_NAME])
            .status();

        if status.is_ok() && status.unwrap().success() {
            println!("✓ Service started successfully!");
        } else {
            println!("⚠  Failed to start service. Check logs: sudo journalctl -u {} -f", SERVICE_NAME);
        }
    }

    println!("\nUseful commands:");
    println!("  Status: sudo systemctl status {}", SERVICE_NAME);
    println!("  Logs:   sudo journalctl -u {} -f", SERVICE_NAME);
    println!("  Stop:   sudo systemctl stop {}", SERVICE_NAME);
    println!("  Start:  sudo systemctl start {}", SERVICE_NAME);

    Ok(())
}

/// Uninstall the system service
async fn uninstall_service() -> Result<()> {
    #[cfg(windows)]
    {
        service::windows::uninstall()
    }

    #[cfg(target_os = "linux")]
    {
        uninstall_systemd_service().await
    }

    #[cfg(target_os = "macos")]
    {
        todo!("macOS service uninstallation not yet implemented");
    }
}

/// Uninstall systemd service (Linux)
#[cfg(target_os = "linux")]
async fn uninstall_systemd_service() -> Result<()> {
    use std::process::Command;

    const SERVICE_NAME: &str = "gururmm-agent";
    const INSTALL_DIR: &str = "/usr/local/bin";
    const CONFIG_DIR: &str = "/etc/gururmm";
    const SYSTEMD_DIR: &str = "/etc/systemd/system";

    info!("Uninstalling GuruRMM Agent...");

    if !nix::unistd::geteuid().is_root() {
        anyhow::bail!("Uninstallation requires root privileges. Please run with sudo.");
    }

    let binary_path = format!("{}/{}", INSTALL_DIR, SERVICE_NAME);
    let unit_file = format!("{}/{}.service", SYSTEMD_DIR, SERVICE_NAME);

    // Stop the service if running
    info!("Stopping service...");
    let _ = Command::new("systemctl")
        .args(["stop", SERVICE_NAME])
        .status();

    // Disable the service
    info!("Disabling service...");
    let _ = Command::new("systemctl")
        .args(["disable", SERVICE_NAME])
        .status();

    // Remove unit file
    if std::path::Path::new(&unit_file).exists() {
        info!("Removing unit file: {}", unit_file);
        std::fs::remove_file(&unit_file)?;
    }

    // Remove binary
    if std::path::Path::new(&binary_path).exists() {
        info!("Removing binary: {}", binary_path);
        std::fs::remove_file(&binary_path)?;
    }

    // Reload systemd
    let _ = Command::new("systemctl")
        .args(["daemon-reload"])
        .status();

    println!("\n✓ GuruRMM Agent uninstalled successfully!");
    println!("\nNote: Config directory {} was preserved.", CONFIG_DIR);
    println!("Remove it manually if no longer needed: sudo rm -rf {}", CONFIG_DIR);

    Ok(())
}

/// Start the installed service
async fn start_service() -> Result<()> {
    #[cfg(windows)]
    {
        service::windows::start()
    }

    #[cfg(target_os = "linux")]
    {
        use std::process::Command;

        info!("Starting GuruRMM Agent service...");

        let status = Command::new("systemctl")
            .args(["start", "gururmm-agent"])
            .status()
            .context("Failed to start service")?;

        if status.success() {
            println!("** Service started successfully");
            println!("Check status: sudo systemctl status gururmm-agent");
        } else {
            anyhow::bail!("Failed to start service. Check: sudo journalctl -u gururmm-agent -n 50");
        }

        Ok(())
    }

    #[cfg(target_os = "macos")]
    {
        todo!("macOS service start not yet implemented");
    }
}

/// Stop the installed service
async fn stop_service() -> Result<()> {
    #[cfg(windows)]
    {
        service::windows::stop()
    }

    #[cfg(target_os = "linux")]
    {
        use std::process::Command;

        info!("Stopping GuruRMM Agent service...");

        let status = Command::new("systemctl")
            .args(["stop", "gururmm-agent"])
            .status()
            .context("Failed to stop service")?;

        if status.success() {
            println!("** Service stopped successfully");
        } else {
            anyhow::bail!("Failed to stop service");
        }

        Ok(())
    }

    #[cfg(target_os = "macos")]
    {
        todo!("macOS service stop not yet implemented");
    }
}

/// Show agent status
async fn show_status(config_path: PathBuf) -> Result<()> {
    // On Windows, show service status
    #[cfg(windows)]
    {
        service::windows::status()?;
        println!();
    }

    // Try to load config for additional info
    match AgentConfig::load(&config_path) {
        Ok(config) => {
            println!("Configuration");
            println!("=============");
            println!("Config file: {:?}", config_path);
            println!("Server URL: {}", config.server.url);
            println!("Metrics interval: {} seconds", config.metrics.interval_seconds);
            println!("Watchdog enabled: {}", config.watchdog.enabled);

            // Collect current metrics
            let collector = MetricsCollector::new();
            let metrics = collector.collect().await;

            println!("\nCurrent System Metrics:");
            println!("  CPU Usage: {:.1}%", metrics.cpu_percent);
            println!("  Memory Usage: {:.1}%", metrics.memory_percent);
            println!(
                "  Memory Used: {:.2} GB",
                metrics.memory_used_bytes as f64 / 1_073_741_824.0
            );
            println!("  Disk Usage: {:.1}%", metrics.disk_percent);
            println!(
                "  Disk Used: {:.2} GB",
                metrics.disk_used_bytes as f64 / 1_073_741_824.0
            );
        }
        Err(_) => {
            println!("\nConfig file {:?} not found or invalid.", config_path);
            #[cfg(windows)]
            println!("Service config location: {}\\agent.toml", service::windows::CONFIG_DIR);
        }
    }

    Ok(())
}

/// Generate a sample configuration file
async fn generate_config(output: PathBuf) -> Result<()> {
    let sample_config = AgentConfig::sample();
    let toml_str = toml::to_string_pretty(&sample_config)?;

    std::fs::write(&output, toml_str)?;
    println!("Sample configuration written to {:?}", output);
    println!("\nEdit this file with your server URL and API key, then run:");
    println!("  gururmm-agent --config {:?} run", output);

    Ok(())
}