1mod profiles;
2
3use std::path::{Path, PathBuf};
4use std::time::Duration;
5
6use clap::{Parser, Subcommand};
7
8use crate::config::AppConfig;
9use crate::core::ProxyCore;
10use crate::core::xray::XrayCore;
11use crate::engine::Watchdog;
12use crate::error::{PilotError, Result};
13use crate::notify::Notifier;
14use crate::notify::bale::BaleNotifier;
15use crate::probe::HealthProbe;
16use crate::probe::http::HttpHealthProbe;
17
18#[derive(Debug, Parser)]
19#[command(
20 name = "proxy-pilot",
21 version,
22 about = "Proxy health monitor and automatic failover daemon"
23)]
24pub struct Cli {
25 #[command(subcommand)]
26 pub command: Commands,
27}
28
29#[derive(Debug, Subcommand)]
30pub enum Commands {
31 Setup,
33 Run {
35 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
36 config: PathBuf,
37 },
38 Status {
40 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
41 config: PathBuf,
42 },
43 Add {
45 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
46 config: PathBuf,
47 #[arg(long)]
48 name: String,
49 #[arg(long)]
50 tag: String,
51 #[arg(long)]
52 priority: Option<u32>,
53 },
54 Import {
56 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
57 config: PathBuf,
58 #[arg(short, long)]
59 file: Option<PathBuf>,
60 #[arg(long)]
62 no_benchmark: bool,
63 links: Vec<String>,
65 },
66 Remove {
68 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
69 config: PathBuf,
70 #[arg(long)]
71 name: String,
72 },
73 List {
75 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
76 config: PathBuf,
77 },
78 Benchmark {
80 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
81 config: PathBuf,
82 },
83 Prune {
85 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
86 config: PathBuf,
87 },
88}
89
90pub async fn dispatch(cli: Cli) -> Result<()> {
91 match cli.command {
92 Commands::Setup => {
93 println!("Interactive setup wizard is planned for the next milestone.");
94 println!("For now, copy config.example.yaml to /etc/proxy-pilot/config.yaml.");
95 Ok(())
96 }
97 Commands::Run { config } => run_daemon(&config).await,
98 Commands::Status { config } => show_status(&config).await,
99 Commands::Add {
100 config,
101 name,
102 tag,
103 priority,
104 } => profiles::add_profile(&config, name, tag, priority).await,
105 Commands::Import {
106 config,
107 file,
108 no_benchmark,
109 links,
110 } => profiles::import_profiles(&config, file.as_deref(), &links, !no_benchmark).await,
111 Commands::Remove { config, name } => profiles::remove_profile(&config, &name).await,
112 Commands::List { config } => profiles::list_profiles(&config).await,
113 Commands::Benchmark { config } => profiles::run_benchmark(&config, false).await,
114 Commands::Prune { config } => profiles::run_benchmark(&config, true).await,
115 }
116}
117
118pub(super) fn build_core(cfg: &AppConfig) -> Result<Box<dyn ProxyCore>> {
119 match cfg.core.kind.as_str() {
120 "xray" => Ok(Box::new(XrayCore::new(
121 &cfg.core.binary_path,
122 &cfg.core.config_path,
123 cfg.core.service_name.clone(),
124 ))),
125 other => Err(PilotError::Config(format!(
126 "unsupported core kind: {other}"
127 ))),
128 }
129}
130
131fn build_notifiers(cfg: &AppConfig) -> Result<Vec<Box<dyn Notifier>>> {
132 let mut list: Vec<Box<dyn Notifier>> = Vec::new();
133 if let Some(bale) = &cfg.notify.bale
134 && bale.enabled
135 {
136 list.push(Box::new(BaleNotifier::new(
137 bale.resolved_token(),
138 bale.chat_id.clone(),
139 )?));
140 }
141 Ok(list)
142}
143
144async fn run_daemon(config_path: &Path) -> Result<()> {
145 let cfg = AppConfig::load(config_path).await?;
146 let timeout = Duration::from_secs(cfg.probe.timeout_secs);
147 let core = build_core(&cfg)?;
148 let probe: Box<dyn HealthProbe> =
149 Box::new(HttpHealthProbe::new(&cfg.core.local_proxy, timeout)?);
150 let notifiers = build_notifiers(&cfg)?;
151
152 let mut watchdog = Watchdog::new(cfg, core, probe, notifiers)
153 .with_direct_probe(Box::new(HttpHealthProbe::direct(timeout)?))
154 .with_periodic_benchmark(
155 Some(config_path.to_path_buf()),
156 Box::new(move |endpoint| Ok(Box::new(HttpHealthProbe::new(endpoint, timeout)?))),
157 );
158 watchdog.run_forever().await
159}
160
161async fn show_status(config_path: &Path) -> Result<()> {
162 let cfg = AppConfig::load_raw(config_path).await?;
163 let core = build_core(&cfg)?;
164 let installed = core.is_installed().await;
165 let active = core.active_profile().await.unwrap_or(None);
166
167 println!("Core: {} (installed: {installed})", core.name());
168 println!("Active: {}", active.as_deref().unwrap_or("unknown"));
169 println!("Profiles: {}", cfg.profiles.len());
170 println!("Targets: {}", cfg.probe.targets.len());
171 Ok(())
172}