use anyhow::{Result, anyhow};
use crate::config::StartupConfig;
use crate::platform::{Platform, current_platform};
use crate::scope::Scope;
pub struct Startup {
config: StartupConfig,
scope: Scope,
platform: Box<dyn Platform>,
}
impl Startup {
pub fn root(config: StartupConfig) -> Result<Self> {
Self::new(config, Scope::Root)
}
pub fn user(config: StartupConfig) -> Result<Self> {
Self::new(config, Scope::User)
}
pub fn exists(&self) -> Result<bool> {
self.platform.exists(&self.config, self.scope)
}
pub fn is_run(&self) -> Result<bool> {
if self.not_installed()? {
return Ok(false);
}
self.running()
}
pub fn install(&self) -> Result<()> {
if self.exists()? {
return Ok(());
}
self.platform.install(&self.config, self.scope)
}
pub fn install_force(&self) -> Result<()> {
self.platform.install(&self.config, self.scope)
}
pub fn uninstall(&self) -> Result<()> {
if self.not_installed()? {
return Ok(());
}
self.platform.uninstall(&self.config, self.scope)
}
pub fn start(&self) -> Result<()> {
if self.not_installed()? || self.running()? {
return Ok(());
}
self.platform.start(&self.config, self.scope)
}
pub fn stop(&self) -> Result<()> {
if self.not_installed()? || !self.running()? {
return Ok(());
}
self.platform.stop(&self.config, self.scope)
}
pub fn restart(&self) -> Result<()> {
if self.not_installed()? {
return Ok(());
}
if self.running()? {
let _ = self.platform.stop(&self.config, self.scope);
}
self.platform.start(&self.config, self.scope)
}
fn running(&self) -> Result<bool> {
self.platform.is_run(&self.config, self.scope)
}
fn not_installed(&self) -> Result<bool> {
if self.exists()? {
return Ok(false);
}
if self.config.ignore_not_installed {
return Ok(true);
}
Err(anyhow!("自启 {} 未注册", self.config.name))
}
fn new(config: StartupConfig, scope: Scope) -> Result<Self> {
Ok(Self {
config: config.resolve()?,
scope,
platform: current_platform()?,
})
}
}