use log::{info};
use std::path::Path;
use std::process::Command;
use crate::error::DaemonError;
pub struct Binary {
path: String,
}
impl Binary {
pub fn new(path: String) -> Self {
Binary { path }
}
pub fn load(&self) -> Result<(), DaemonError> {
info!("Loading binary: {}", self.path);
if !Path::new(&self.path).exists() {
return Err(DaemonError::CustomError(format!("Binary not found: {}", self.path)));
}
let output = Command::new(&self.path)
.output()
.map_err(|e| DaemonError::CustomError(format!("Failed to execute binary: {}", e)))?;
if !output.status.success() {
return Err(DaemonError::CustomError(format!(
"Binary failed with output: {}",
String::from_utf8_lossy(&output.stderr)
)));
}
info!("Successfully loaded binary: {}", self.path);
Ok(())
}
pub fn unload(&self) -> Result<(), DaemonError> {
info!("Unloading binary: {}", self.path);
let output = Command::new("pkill")
.arg(&self.path)
.output()
.map_err(|e| DaemonError::CustomError(format!("Failed to unload binary: {}", e)))?;
if !output.status.success() {
return Err(DaemonError::CustomError(format!(
"Failed to unload binary: {}",
String::from_utf8_lossy(&output.stderr)
)));
}
info!("Successfully unloaded binary: {}", self.path);
Ok(())
}
}
pub struct BinaryManager {
binaries: Vec<Binary>,
}
impl BinaryManager {
pub fn new(binaries: Vec<String>) -> Self {
BinaryManager {
binaries: binaries.into_iter().map(Binary::new).collect(),
}
}
pub fn load_all(&self) -> Result<(), DaemonError> {
for binary in &self.binaries {
binary.load()?;
}
Ok(())
}
pub fn unload_all(&self) -> Result<(), DaemonError> {
for binary in &self.binaries {
binary.unload()?;
}
Ok(())
}
}