wakezilla 0.2.1

A Wake-on-LAN proxy server written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! Interactive `setup` wizard: configure and install a Wakezilla system service.

use anyhow::{Context, Result};
use clap::Parser;

use crate::config::{self, Config};
use crate::service::{self, Mode};

/// CLI arguments for the `setup` subcommand.
#[derive(Parser, Debug, Default)]
#[command()]
pub struct SetupArgs {
    /// Pre-select the mode ("proxy" or "client"); skips the TUI prompt if combined with --port.
    #[arg(long, help_heading = "Setup Options")]
    pub mode: Option<String>,

    /// Pre-select the port; skips the TUI prompt if combined with --mode.
    #[arg(long, help_heading = "Setup Options")]
    pub port: Option<u16>,

    /// Skip the overwrite confirmation prompt (for non-interactive use).
    #[arg(long, short = 'y', help_heading = "Setup Options")]
    pub yes: bool,
}

/// Action for the `service` subcommand.
#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
pub enum ServiceAction {
    Start,
    Stop,
    Restart,
    /// Report whether the service is running.
    Status,
    /// Show the service's logs (prints status first).
    Logs,
}

/// CLI arguments for the `service` subcommand.
#[derive(Parser, Debug)]
#[command()]
pub struct ServiceArgs {
    /// Action to perform on the installed service.
    #[arg(value_enum)]
    pub action: ServiceAction,

    /// Target server ("proxy" or "client"); skips the TUI prompt.
    #[arg(long, help_heading = "Service Options")]
    pub mode: Option<String>,

    /// For `logs`: keep streaming new output until interrupted.
    #[arg(long, short = 'f', help_heading = "Service Options")]
    pub follow: bool,

    /// For `logs`: number of trailing lines to show (default 50).
    #[arg(long, short = 'n', help_heading = "Service Options")]
    pub lines: Option<u32>,
}

/// Build a Config with the chosen port placed in the correct field for `mode`.
pub fn build_config(mode: Mode, port: u16) -> Config {
    let mut cfg = Config::default();
    match mode {
        Mode::Proxy => cfg.server.proxy_port = port,
        Mode::Client => cfg.server.client_port = port,
    }
    cfg
}

/// Write the config file, install the service, and validate it.
/// Returns the config path on success.
///
/// If a config file already exists, its other settings (e.g. the other server's
/// port) are preserved; only the target mode's port is updated.
pub fn apply(mode: Mode, port: u16) -> Result<std::path::PathBuf> {
    let exe = std::env::current_exe().context("failed to resolve current executable path")?;
    let exe = exe.to_string_lossy().to_string();

    let path = config::config_path();
    let mut cfg = if path.exists() {
        Config::load_from(&path).unwrap_or_else(|_| build_config(mode, port))
    } else {
        build_config(mode, port)
    };
    match mode {
        Mode::Proxy => cfg.server.proxy_port = port,
        Mode::Client => cfg.server.client_port = port,
    }
    cfg.save_to(&path)
        .with_context(|| format!("failed to write config to {}", path.display()))?;

    service::install(mode, &exe).context("failed to install system service")?;
    service::validate(port, 10).context("service installed but did not become reachable")?;

    Ok(path)
}

/// Summarize any existing Wakezilla configuration/services on this host.
/// Returns `None` if nothing is installed and no config file exists.
fn existing_summary() -> Option<String> {
    let installed = service::installed_modes();
    let path = config::config_path();
    let cfg_exists = path.exists();
    if installed.is_empty() && !cfg_exists {
        return None;
    }

    let mut lines = Vec::new();
    if cfg_exists {
        if let Ok(cfg) = Config::load_from(&path) {
            lines.push(format!(
                "  config: {} (proxy_port={}, client_port={})",
                path.display(),
                cfg.server.proxy_port,
                cfg.server.client_port
            ));
        } else {
            lines.push(format!("  config: {}", path.display()));
        }
    }
    if !installed.is_empty() {
        let names: Vec<&str> = installed.iter().map(|m| m.subcommand()).collect();
        lines.push(format!("  installed services: {}", names.join(", ")));
    }
    Some(lines.join("\n"))
}

/// Prompt the operator to confirm overwriting an existing configuration.
/// Returns `Ok(true)` when there is nothing to overwrite or the user confirms.
fn confirm_overwrite() -> Result<bool> {
    let Some(summary) = existing_summary() else {
        return Ok(true);
    };

    println!("An existing Wakezilla configuration was detected:");
    println!("{summary}");
    print!("Overwrite / reconfigure? [y/N]: ");
    std::io::stdout().flush().ok();

    let mut input = String::new();
    std::io::stdin()
        .read_line(&mut input)
        .context("failed to read confirmation")?;
    Ok(matches!(
        input.trim().to_ascii_lowercase().as_str(),
        "y" | "yes"
    ))
}

use std::io;
use std::io::Write;
use std::time::Duration;

use crossterm::{
    event::{self, Event, KeyCode, KeyModifiers},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
    backend::CrosstermBackend,
    layout::{Constraint, Direction, Layout},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph},
    Frame, Terminal,
};

/// Wizard entry point. Requires elevation. Falls back to the TUI when the mode/port
/// are not both provided on the command line.
pub fn run(args: SetupArgs) -> Result<()> {
    if !service::is_elevated() {
        eprintln!(
            "wakezilla setup must run with administrator privileges.\n\
             Re-run with: sudo wakezilla setup   (Linux/macOS)  or  an elevated shell (Windows)."
        );
        std::process::exit(1);
    }

    let skip_confirm = args.yes;

    // Headless path: both flags provided.
    if let (Some(mode_str), Some(port)) = (&args.mode, args.port) {
        let mode = Mode::from_str_opt(mode_str)
            .with_context(|| format!("invalid --mode '{mode_str}' (use 'proxy' or 'client')"))?;
        if !skip_confirm && !confirm_overwrite()? {
            println!("Aborted; no changes made.");
            return Ok(());
        }
        let path = apply(mode, port)?;
        println!(
            "Configured {} on port {port}. Config written to {}.",
            mode.subcommand(),
            path.display()
        );
        return Ok(());
    }

    let (mode, port) = run_wizard(args)?;
    if !skip_confirm && !confirm_overwrite()? {
        println!("Aborted; no changes made.");
        return Ok(());
    }
    let path = apply(mode, port)?;
    println!(
        "Configured {} on port {port}. Config written to {}.",
        mode.subcommand(),
        path.display()
    );
    Ok(())
}

#[derive(PartialEq)]
enum Step {
    ModeSelect,
    PortInput,
    Confirm,
}

struct Wizard {
    step: Step,
    mode: Mode,
    port_input: String,
    error: Option<String>,
}

impl Wizard {
    fn new(args: &SetupArgs) -> Self {
        let mode = args
            .mode
            .as_deref()
            .and_then(Mode::from_str_opt)
            .unwrap_or(Mode::Proxy);
        Wizard {
            step: Step::ModeSelect,
            mode,
            port_input: args
                .port
                .map(|p| p.to_string())
                .unwrap_or_else(|| mode.default_port().to_string()),
            error: None,
        }
    }
}

/// Run the interactive wizard, returning the chosen (mode, port).
fn run_wizard(args: SetupArgs) -> Result<(Mode, u16)> {
    enable_raw_mode().context("failed to enable raw mode")?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen).context("failed to enter alt screen")?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend).context("failed to create terminal")?;

    let result = wizard_loop(&mut terminal, args);

    disable_raw_mode().ok();
    execute!(terminal.backend_mut(), LeaveAlternateScreen).ok();
    terminal.show_cursor().ok();

    result
}

fn wizard_loop<B: ratatui::backend::Backend>(
    terminal: &mut Terminal<B>,
    args: SetupArgs,
) -> Result<(Mode, u16)> {
    let mut w = Wizard::new(&args);

    loop {
        terminal.draw(|f| draw_wizard(f, &w))?;

        if !event::poll(Duration::from_millis(200))? {
            continue;
        }
        if let Event::Key(key) = event::read()? {
            // Ctrl-C / Esc aborts.
            if key.code == KeyCode::Esc
                || (key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL))
            {
                return Err(anyhow::anyhow!("setup cancelled"));
            }

            match w.step {
                Step::ModeSelect => match key.code {
                    KeyCode::Left | KeyCode::Right | KeyCode::Char('h') | KeyCode::Char('l') => {
                        w.mode = match w.mode {
                            Mode::Proxy => Mode::Client,
                            Mode::Client => Mode::Proxy,
                        };
                        w.port_input = w.mode.default_port().to_string();
                    }
                    KeyCode::Enter => w.step = Step::PortInput,
                    _ => {}
                },
                Step::PortInput => match key.code {
                    KeyCode::Char(c) if c.is_ascii_digit() && w.port_input.len() < 5 => {
                        w.port_input.push(c);
                    }
                    KeyCode::Backspace => {
                        w.port_input.pop();
                    }
                    KeyCode::Enter => match w.port_input.parse::<u16>() {
                        Ok(p) if p > 0 => {
                            w.error = None;
                            w.step = Step::Confirm;
                        }
                        _ => w.error = Some("Enter a valid port (1-65535)".to_string()),
                    },
                    _ => {}
                },
                Step::Confirm => match key.code {
                    KeyCode::Enter => {
                        let port: u16 = w.port_input.parse().unwrap_or(w.mode.default_port());
                        return Ok((w.mode, port));
                    }
                    KeyCode::Char('b') => w.step = Step::PortInput,
                    _ => {}
                },
            }
        }
    }
}

fn draw_wizard(f: &mut Frame, w: &Wizard) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3),
            Constraint::Min(6),
            Constraint::Length(3),
        ])
        .split(f.area());

    let title = Paragraph::new("Wakezilla Setup")
        .style(Style::default().add_modifier(Modifier::BOLD))
        .block(Block::default().borders(Borders::ALL));
    f.render_widget(title, chunks[0]);

    let body = match w.step {
        Step::ModeSelect => {
            let proxy = mode_span("Proxy server", w.mode == Mode::Proxy);
            let client = mode_span("Client server", w.mode == Mode::Client);
            vec![
                Line::from(
                    "What do you want to configure? (Left/Right to switch, Enter to confirm)",
                ),
                Line::from(""),
                Line::from(vec![proxy, Span::raw("   "), client]),
            ]
        }
        Step::PortInput => vec![
            Line::from(format!(
                "Port for {} (Enter to confirm):",
                w.mode.subcommand()
            )),
            Line::from(""),
            Line::from(Span::styled(
                format!("> {}", w.port_input),
                Style::default().add_modifier(Modifier::BOLD),
            )),
        ],
        Step::Confirm => vec![
            Line::from("Confirm configuration (Enter to apply, 'b' to go back):"),
            Line::from(""),
            Line::from(format!("  Mode: {}", w.mode.subcommand())),
            Line::from(format!("  Port: {}", w.port_input)),
            Line::from(format!("  Config: {}", config::config_path().display())),
        ],
    };

    let mut lines = body;
    if let Some(err) = &w.error {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            err.clone(),
            Style::default().add_modifier(Modifier::BOLD),
        )));
    }

    let para = Paragraph::new(lines).block(Block::default().borders(Borders::ALL));
    f.render_widget(para, chunks[1]);

    let footer =
        Paragraph::new("Esc / Ctrl-C: cancel").block(Block::default().borders(Borders::ALL));
    f.render_widget(footer, chunks[2]);
}

fn mode_span(label: &str, selected: bool) -> Span<'static> {
    let text = if selected {
        format!("[ {label} ]")
    } else {
        format!("  {label}  ")
    };
    let style = if selected {
        Style::default().add_modifier(Modifier::REVERSED | Modifier::BOLD)
    } else {
        Style::default()
    };
    Span::styled(text, style)
}

/// Entry point for the `service` subcommand: start/stop/restart/status/logs of an
/// installed service. Requires elevation. Resolves the target mode from `--mode`, a
/// single install, or a TUI picker when both proxy and client are installed.
pub fn run_service(args: ServiceArgs) -> Result<()> {
    if !service::is_elevated() {
        eprintln!(
            "wakezilla service must run with administrator privileges.\n\
             Re-run with: sudo wakezilla service <action>   (Linux/macOS)  or  an elevated shell (Windows)."
        );
        std::process::exit(1);
    }

    let mode = match &args.mode {
        Some(mode_str) => {
            let mode = Mode::from_str_opt(mode_str).with_context(|| {
                format!("invalid --mode '{mode_str}' (use 'proxy' or 'client')")
            })?;
            if !service::is_installed(mode) {
                anyhow::bail!(
                    "{} service is not installed. Run `wakezilla setup` first.",
                    mode.subcommand()
                );
            }
            mode
        }
        None => {
            let installed = service::installed_modes();
            match installed.as_slice() {
                [] => {
                    anyhow::bail!("No Wakezilla service is installed. Run `wakezilla setup` first.")
                }
                [only] => *only,
                _ => pick_mode(&installed)?,
            }
        }
    };

    match args.action {
        ServiceAction::Start => {
            service::start(mode).context("failed to start service")?;
            println!("{} service started.", mode.subcommand());
        }
        ServiceAction::Stop => {
            service::stop(mode).context("failed to stop service")?;
            println!("{} service stopped.", mode.subcommand());
        }
        ServiceAction::Restart => {
            service::restart(mode).context("failed to restart service")?;
            println!("{} service restarted.", mode.subcommand());
        }
        ServiceAction::Status => print_status(mode),
        ServiceAction::Logs => {
            print_status(mode);
            println!("--- logs ---");
            service::logs(mode, args.follow, args.lines.unwrap_or(50))
                .context("failed to show logs")?;
        }
    }
    Ok(())
}

/// Print whether the service for `mode` is currently running.
fn print_status(mode: Mode) {
    let state = if service::is_running(mode) {
        "running"
    } else {
        "stopped"
    };
    println!("{} service: {state}", mode.subcommand());
}

/// Interactive picker to choose one mode from the installed set (Left/Right, Enter).
fn pick_mode(modes: &[Mode]) -> Result<Mode> {
    enable_raw_mode().context("failed to enable raw mode")?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen).context("failed to enter alt screen")?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend).context("failed to create terminal")?;

    let result = pick_mode_loop(&mut terminal, modes);

    disable_raw_mode().ok();
    execute!(terminal.backend_mut(), LeaveAlternateScreen).ok();
    terminal.show_cursor().ok();

    result
}

fn pick_mode_loop<B: ratatui::backend::Backend>(
    terminal: &mut Terminal<B>,
    modes: &[Mode],
) -> Result<Mode> {
    let mut selected = 0usize;

    loop {
        terminal.draw(|f| draw_pick_mode(f, modes, selected))?;

        if !event::poll(Duration::from_millis(200))? {
            continue;
        }
        if let Event::Key(key) = event::read()? {
            if key.code == KeyCode::Esc
                || (key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL))
            {
                return Err(anyhow::anyhow!("cancelled"));
            }
            match key.code {
                KeyCode::Left | KeyCode::Right | KeyCode::Char('h') | KeyCode::Char('l') => {
                    selected = (selected + 1) % modes.len();
                }
                KeyCode::Enter => return Ok(modes[selected]),
                _ => {}
            }
        }
    }
}

fn draw_pick_mode(f: &mut Frame, modes: &[Mode], selected: usize) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3),
            Constraint::Min(4),
            Constraint::Length(3),
        ])
        .split(f.area());

    let title = Paragraph::new("Wakezilla Service")
        .style(Style::default().add_modifier(Modifier::BOLD))
        .block(Block::default().borders(Borders::ALL));
    f.render_widget(title, chunks[0]);

    let spans: Vec<Span> = modes
        .iter()
        .enumerate()
        .flat_map(|(i, m)| {
            let label = match m {
                Mode::Proxy => "Proxy server",
                Mode::Client => "Client server",
            };
            vec![mode_span(label, i == selected), Span::raw("   ")]
        })
        .collect();

    let body = vec![
        Line::from("Which service? (Left/Right to switch, Enter to select)"),
        Line::from(""),
        Line::from(spans),
    ];
    let para = Paragraph::new(body).block(Block::default().borders(Borders::ALL));
    f.render_widget(para, chunks[1]);

    let footer =
        Paragraph::new("Esc / Ctrl-C: cancel").block(Block::default().borders(Borders::ALL));
    f.render_widget(footer, chunks[2]);
}