navi-notifier 0.3.0

A friendly helper to guide you through the day-to-day noise of code review.
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! `navi service`: install, remove, or check the background service that runs
//! `navi run` on login. A systemd user unit on Linux, a launchd agent on macOS,
//! and a Task Scheduler logon task on Windows.
//!
//! The service does not inherit your interactive shell's environment, so tokens
//! have to reach it another way: on Linux/macOS the generated unit sources a
//! `navi.env` file kept next to the config (created here, chmod 600); on Windows
//! the logon task inherits user-scope variables you set with `setx`.

use std::env;
use std::fs;
use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{bail, Context, Result};
use tempfile::NamedTempFile;

use crate::prompt::confirm;

/// launchd label and Task Scheduler task name; also used to locate them again.
const LAUNCHD_LABEL: &str = "dev.navi.navi";
const WINDOWS_TASK_NAME: &str = "Navi";
/// Where the logon task appends navi's output. PowerShell env-expands this in the
/// task action; the `%VAR%` form is what we print to the user.
const WINDOWS_LOG_DISPLAY: &str = r"%LOCALAPPDATA%\navi\navi.log";
/// Roll `navi.log` to `navi.log.1` when it exceeds this, checked each time the task
/// starts. Caps growth across restarts (upgrades, logon, reboot) - Windows won't
/// let us rotate the file while the running task holds it open for append.
const WINDOWS_LOG_MAX_BYTES: u64 = 10 * 1024 * 1024;

/// Install and start the background service for the current OS.
pub fn install(config_path: &Path, yes: bool) -> Result<()> {
    let exe = current_exe_string()?;
    match env::consts::OS {
        "linux" => install_systemd(&exe, config_path, yes),
        "macos" => install_launchd(&exe, config_path, yes),
        "windows" => install_task(&exe, config_path, yes),
        other => bail!(
            "no background-service integration for {other}; run `navi run` under your own supervisor"
        ),
    }
}

/// Stop and remove the background service for the current OS.
pub fn uninstall(yes: bool) -> Result<()> {
    match env::consts::OS {
        "linux" => uninstall_systemd(yes),
        "macos" => uninstall_launchd(yes),
        "windows" => uninstall_task(yes),
        other => bail!("no background-service integration for {other}"),
    }
}

/// Report whether the background service is installed and running.
pub fn status() -> Result<()> {
    match env::consts::OS {
        "linux" => status_systemd(),
        "macos" => status_launchd(),
        "windows" => status_task(),
        other => bail!("no background-service integration for {other}"),
    }
}

/// Offer to install the service right after `navi init`, but only at a real
/// terminal on a supported OS. Declining is a no-op with a hint.
pub fn offer_after_init(config_path: &Path) -> Result<()> {
    if !std::io::stdin().is_terminal() {
        return Ok(());
    }
    let kind = match env::consts::OS {
        "linux" => "a systemd user service",
        "macos" => "a launchd agent",
        "windows" => "a Task Scheduler logon task",
        _ => return Ok(()),
    };
    if confirm(&format!(
        "Run navi in the background on login? Installs {kind}. [y/N] "
    ))? {
        install(config_path, true)?;
    } else {
        println!("Skipped; enable it later with `navi service install`.");
    }
    Ok(())
}

/// After an upgrade/downgrade, restart the installed background service so it runs
/// the freshly installed binary (the daemon is otherwise stuck on the old one in
/// memory until a reboot). On Linux it also warns and skips the restart when the
/// unit's `ExecStart` points at a different binary than the one just installed
/// (the `~/.cargo/bin` template trap); macOS/Windows just restart, since their
/// services are generated by `navi service install` from the running binary rather
/// than a hand-copied template - a divergent path there would be a follow-up.
/// A no-op when no service is installed.
pub fn restart_after_upgrade(do_restart: bool) -> Result<()> {
    match env::consts::OS {
        "linux" => restart_systemd(do_restart),
        "macos" => restart_launchd(do_restart),
        "windows" => restart_task(do_restart),
        _ => Ok(()),
    }
}

/// `navi service restart`: restart the installed background service so it re-reads
/// config and `navi.env`. User-invoked, so a missing service is an error with an
/// install hint (unlike `restart_after_upgrade`, which silently no-ops). It also
/// skips the upgrade path's ExecStart-mismatch check: the user asked to restart
/// whatever is installed, so honor that rather than second-guessing the binary.
pub fn restart() -> Result<()> {
    match env::consts::OS {
        "linux" => {
            if systemd_unit_path().is_none() {
                bail!("no navi.service installed; run `navi service install` first");
            }
            run(Command::new("systemctl").args(["--user", "restart", "navi.service"]))?;
            println!("restarted navi.service (re-reads config and navi.env on start)");
        }
        "macos" => {
            let Some(plist) = launchd_plist_path() else {
                bail!("no launchd agent installed; run `navi service install` first");
            };
            let _ = Command::new("launchctl")
                .args(["unload", "-w"])
                .arg(&plist)
                .status();
            run(Command::new("launchctl").args(["load", "-w"]).arg(&plist))?;
            println!("restarted the launchd agent (re-reads config and navi.env on start)");
        }
        "windows" => {
            if !task_exists() {
                bail!("no '{WINDOWS_TASK_NAME}' task installed; run `navi service install` first");
            }
            let _ = Command::new("schtasks")
                .args(["/End", "/TN", WINDOWS_TASK_NAME])
                .status();
            run(Command::new("schtasks").args(["/Run", "/TN", WINDOWS_TASK_NAME]))?;
            println!(
                "restarted the '{WINDOWS_TASK_NAME}' task (re-reads config and navi.env on start)"
            );
        }
        other => bail!("no background-service integration for {other}"),
    }
    Ok(())
}

/// Path to the installed systemd user unit, if present.
fn systemd_unit_path() -> Option<PathBuf> {
    let unit = home_dir().ok()?.join(".config/systemd/user/navi.service");
    unit.exists().then_some(unit)
}

/// Path to the installed launchd agent plist, if present.
fn launchd_plist_path() -> Option<PathBuf> {
    let plist = home_dir()
        .ok()?
        .join("Library/LaunchAgents")
        .join(format!("{LAUNCHD_LABEL}.plist"));
    plist.exists().then_some(plist)
}

/// Whether the Windows logon task is registered.
fn task_exists() -> bool {
    Command::new("schtasks")
        .args(["/Query", "/TN", WINDOWS_TASK_NAME])
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

fn restart_systemd(do_restart: bool) -> Result<()> {
    let Some(unit) = systemd_unit_path() else {
        return Ok(());
    };
    if let Some(exec) = systemd_exec_path(&unit) {
        if !exec_is_current(&exec) {
            warn_exec_mismatch(&exec);
            return Ok(());
        }
    }
    if !do_restart {
        println!("service left as-is; restart it with: systemctl --user restart navi.service");
        return Ok(());
    }
    run(Command::new("systemctl").args(["--user", "restart", "navi.service"]))?;
    println!("restarted navi.service on the new version");
    Ok(())
}

fn restart_launchd(do_restart: bool) -> Result<()> {
    let Some(plist) = launchd_plist_path() else {
        return Ok(());
    };
    if !do_restart {
        println!(
            "agent left as-is; reload it: launchctl unload -w \"{p}\" && launchctl load -w \"{p}\"",
            p = plist.display()
        );
        return Ok(());
    }
    let _ = Command::new("launchctl")
        .args(["unload", "-w"])
        .arg(&plist)
        .status();
    run(Command::new("launchctl").args(["load", "-w"]).arg(&plist))?;
    println!("restarted the launchd agent on the new version");
    Ok(())
}

fn restart_task(do_restart: bool) -> Result<()> {
    if !task_exists() {
        return Ok(());
    }
    if !do_restart {
        println!("task left as-is; restart it: schtasks /End /TN {WINDOWS_TASK_NAME} && schtasks /Run /TN {WINDOWS_TASK_NAME}");
        return Ok(());
    }
    let _ = Command::new("schtasks")
        .args(["/End", "/TN", WINDOWS_TASK_NAME])
        .status();
    run(Command::new("schtasks").args(["/Run", "/TN", WINDOWS_TASK_NAME]))?;
    println!("restarted the '{WINDOWS_TASK_NAME}' task on the new version");
    Ok(())
}

/// The program path from a unit's `ExecStart=` line, or `None` if unreadable.
fn systemd_exec_path(unit: &Path) -> Option<PathBuf> {
    let text = fs::read_to_string(unit).ok()?;
    let value = text
        .lines()
        .find_map(|l| l.trim().strip_prefix("ExecStart="))?;
    Some(PathBuf::from(exec_program(value)))
}

/// The program path from an `ExecStart` value: our quoted `"path" args` form, or a
/// bare `path args` form.
fn exec_program(value: &str) -> String {
    let value = value.trim();
    if let Some(rest) = value.strip_prefix('"') {
        rest.split('"').next().unwrap_or(rest).to_string()
    } else {
        value.split_whitespace().next().unwrap_or(value).to_string()
    }
}

/// The binary we're running, with the `(deleted)` suffix stripped - `navi upgrade`
/// replaces its own file under itself, so `/proc/self/exe` reports the path as
/// deleted. This is the path the installer just wrote the new binary to.
fn current_binary() -> Option<PathBuf> {
    let path = env::current_exe().ok()?;
    let text = path.to_string_lossy();
    let cleaned = text.strip_suffix(" (deleted)").unwrap_or(&text);
    Some(PathBuf::from(cleaned))
}

/// Whether the service's program is the same file as the binary the installer just
/// wrote. Symlink-resolved when possible; assumes a match if we can't tell.
fn exec_is_current(exec: &Path) -> bool {
    let Some(current) = current_binary() else {
        return true;
    };
    match (fs::canonicalize(exec), fs::canonicalize(&current)) {
        (Ok(a), Ok(b)) => a == b,
        _ => exec == current,
    }
}

fn warn_exec_mismatch(exec: &Path) {
    let current = current_binary()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| "the newly installed binary".into());
    println!(
        "warning: the service runs {} but the upgrade installed {current}",
        exec.display()
    );
    println!("it will keep running the old binary; regenerate the unit with: navi service install");
}

// ---------------------------------------------------------------------------
// Linux: systemd user service
// ---------------------------------------------------------------------------

fn install_systemd(exe: &str, config: &Path, yes: bool) -> Result<()> {
    let home = home_dir()?;
    let unit_dir = home.join(".config/systemd/user");
    let unit_path = unit_dir.join("navi.service");
    let env_file = env_file_path(config);

    if !approve(
        yes,
        &format!(
            "install systemd user service at {} and enable it? [y/N] ",
            unit_path.display()
        ),
    )? {
        return Ok(());
    }

    fs::create_dir_all(&unit_dir)
        .with_context(|| format!("failed to create {}", unit_dir.display()))?;
    fs::write(&unit_path, systemd_unit(exe, config, &env_file))
        .with_context(|| format!("failed to write {}", unit_path.display()))?;
    ensure_env_file(&env_file)?;

    run(Command::new("systemctl").args(["--user", "daemon-reload"]))?;
    run(Command::new("systemctl").args(["--user", "enable", "--now", "navi.service"]))?;

    println!("installed and started navi.service");
    print_env_hint(&env_file, "systemctl --user restart navi.service");
    println!("logs:  journalctl --user -u navi -f");
    println!("to keep it running while logged out:  loginctl enable-linger \"$USER\"");
    Ok(())
}

fn uninstall_systemd(yes: bool) -> Result<()> {
    let unit_path = home_dir()?.join(".config/systemd/user/navi.service");
    if !unit_path.exists() {
        println!("no navi.service found at {}", unit_path.display());
        return Ok(());
    }
    if !approve(yes, "stop and remove navi.service? [y/N] ")? {
        return Ok(());
    }
    // Best effort: the unit may already be stopped.
    let _ = Command::new("systemctl")
        .args(["--user", "disable", "--now", "navi.service"])
        .status();
    fs::remove_file(&unit_path)
        .with_context(|| format!("failed to remove {}", unit_path.display()))?;
    let _ = Command::new("systemctl")
        .args(["--user", "daemon-reload"])
        .status();
    println!("removed {}", unit_path.display());
    println!("(the navi.env token file, if any, is left in place)");
    Ok(())
}

fn status_systemd() -> Result<()> {
    let enabled = capture(Command::new("systemctl").args(["--user", "is-enabled", "navi.service"]));
    let active = capture(Command::new("systemctl").args(["--user", "is-active", "navi.service"]));
    println!(
        "navi.service: {} ({})",
        active.as_deref().unwrap_or("unknown"),
        enabled.as_deref().unwrap_or("unknown")
    );
    Ok(())
}

/// The `[Unit]`/`[Service]` file. Paths are double-quoted so spaces survive.
fn systemd_unit(exe: &str, config: &Path, env_file: &Path) -> String {
    format!(
        "[Unit]\n\
         Description=navi: focused PR-review alerts\n\
         After=network-online.target\n\
         Wants=network-online.target\n\
         \n\
         [Service]\n\
         Type=simple\n\
         ExecStart=\"{exe}\" run --config \"{config}\"\n\
         EnvironmentFile=-{env_file}\n\
         Restart=on-failure\n\
         RestartSec=10\n\
         \n\
         [Install]\n\
         WantedBy=default.target\n",
        exe = exe,
        config = config.display(),
        env_file = env_file.display(),
    )
}

// ---------------------------------------------------------------------------
// macOS: launchd agent
// ---------------------------------------------------------------------------

fn install_launchd(exe: &str, config: &Path, yes: bool) -> Result<()> {
    let home = home_dir()?;
    let plist_path = home
        .join("Library/LaunchAgents")
        .join(format!("{LAUNCHD_LABEL}.plist"));
    let log = home.join("Library/Logs/navi.log");
    let env_file = env_file_path(config);

    if !approve(
        yes,
        &format!(
            "install launchd agent at {} and load it? [y/N] ",
            plist_path.display()
        ),
    )? {
        return Ok(());
    }

    if let Some(parent) = plist_path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }
    fs::write(&plist_path, launchd_plist(exe, config, &env_file, &log))
        .with_context(|| format!("failed to write {}", plist_path.display()))?;
    ensure_env_file(&env_file)?;

    // Reload cleanly if it was already loaded.
    let _ = Command::new("launchctl")
        .args(["unload", "-w"])
        .arg(&plist_path)
        .status();
    run(Command::new("launchctl")
        .args(["load", "-w"])
        .arg(&plist_path))?;

    println!("installed and loaded {LAUNCHD_LABEL}");
    print_env_hint(
        &env_file,
        &format!(
            "launchctl unload -w \"{p}\" && launchctl load -w \"{p}\"",
            p = plist_path.display()
        ),
    );
    println!("logs:  tail -f {}", log.display());
    Ok(())
}

fn uninstall_launchd(yes: bool) -> Result<()> {
    let plist_path = home_dir()?
        .join("Library/LaunchAgents")
        .join(format!("{LAUNCHD_LABEL}.plist"));
    if !plist_path.exists() {
        println!("no launchd agent found at {}", plist_path.display());
        return Ok(());
    }
    if !approve(yes, "unload and remove the navi launchd agent? [y/N] ")? {
        return Ok(());
    }
    let _ = Command::new("launchctl")
        .args(["unload", "-w"])
        .arg(&plist_path)
        .status();
    fs::remove_file(&plist_path)
        .with_context(|| format!("failed to remove {}", plist_path.display()))?;
    println!("removed {}", plist_path.display());
    println!("(the navi.env token file, if any, is left in place)");
    Ok(())
}

fn status_launchd() -> Result<()> {
    let loaded = Command::new("launchctl")
        .args(["list", LAUNCHD_LABEL])
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    println!(
        "{LAUNCHD_LABEL}: {}",
        if loaded { "loaded" } else { "not loaded" }
    );
    Ok(())
}

/// The launchd plist. `ProgramArguments` runs a shell that sources the env file
/// (launchd has no `EnvironmentFile`) and then execs navi.
fn launchd_plist(exe: &str, config: &Path, env_file: &Path, log: &Path) -> String {
    let run = format!(
        "set -a; [ -f \"{env}\" ] && . \"{env}\"; exec \"{exe}\" run --config \"{config}\"",
        env = env_file.display(),
        exe = exe,
        config = config.display(),
    );
    format!(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
         <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
         <plist version=\"1.0\">\n\
         <dict>\n\
         \x20   <key>Label</key><string>{label}</string>\n\
         \x20   <key>ProgramArguments</key>\n\
         \x20   <array>\n\
         \x20       <string>/bin/sh</string>\n\
         \x20       <string>-c</string>\n\
         \x20       <string>{run}</string>\n\
         \x20   </array>\n\
         \x20   <key>RunAtLoad</key><true/>\n\
         \x20   <key>KeepAlive</key><true/>\n\
         \x20   <key>StandardOutPath</key><string>{log}</string>\n\
         \x20   <key>StandardErrorPath</key><string>{log}</string>\n\
         </dict>\n\
         </plist>\n",
        label = LAUNCHD_LABEL,
        run = xml_escape(&run),
        log = xml_escape(&log.display().to_string()),
    )
}

// ---------------------------------------------------------------------------
// Windows: Task Scheduler logon task
// ---------------------------------------------------------------------------

fn install_task(exe: &str, config: &Path, yes: bool) -> Result<()> {
    if !approve(
        yes,
        &format!("register the '{WINDOWS_TASK_NAME}' logon task to run navi at sign-in? [y/N] "),
    )? {
        return Ok(());
    }
    // Register from an XML file rather than `/TR`: schtasks caps `/TR` at 261 chars,
    // which navi's log-wrapper command overflows (#125). Write UTF-16 so schtasks
    // accepts it, then hand it the path.
    let mut xml = NamedTempFile::new().context("creating the task definition file")?;
    xml.write_all(&utf16le_with_bom(&task_xml(exe, config)))
        .context("writing the task definition")?;
    // Close our handle (keeping the file on disk) before schtasks opens it: Windows
    // won't let schtasks read a file this process still holds open.
    let xml_path = xml.into_temp_path();
    run(Command::new("schtasks")
        .args(["/Create", "/TN", WINDOWS_TASK_NAME, "/XML"])
        .arg(&xml_path)
        .arg("/F"))?;

    println!("registered the '{WINDOWS_TASK_NAME}' task; navi will start at your next sign-in");
    println!("navi runs hidden (no console window); output goes to {WINDOWS_LOG_DISPLAY}");
    println!("start it now with:");
    println!("  schtasks /Run /TN {WINDOWS_TASK_NAME}");
    println!("the task inherits your user environment, so set tokens persistently:");
    println!("  setx NAVI_GITHUB_TOKEN ghp_...");
    println!("  setx NAVI_SLACK_TOKEN xoxb-...");
    println!("(then sign out and back in so the task picks them up)");
    Ok(())
}

fn uninstall_task(yes: bool) -> Result<()> {
    if !approve(
        yes,
        &format!("delete the '{WINDOWS_TASK_NAME}' task? [y/N] "),
    )? {
        return Ok(());
    }
    run(Command::new("schtasks").args(["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"]))?;
    println!("deleted the '{WINDOWS_TASK_NAME}' task");
    Ok(())
}

fn status_task() -> Result<()> {
    let found = Command::new("schtasks")
        .args(["/Query", "/TN", WINDOWS_TASK_NAME])
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    println!(
        "{WINDOWS_TASK_NAME} task: {}",
        if found {
            "registered"
        } else {
            "not registered"
        }
    );
    Ok(())
}

/// The PowerShell arguments that run navi through a hidden window (so no console
/// appears at sign-in) and append all output to a per-user log file, rotating it
/// past a size cap and creating its directory first — a hidden task otherwise has
/// nowhere to log.
fn ps_run_arguments(exe: &str, config: &Path) -> String {
    // Double any single quote so a path like C:\Users\O'Brien\... can't break out
    // of the PowerShell single-quoted string it sits in.
    let exe = ps_single_quote_escape(exe);
    let config = ps_single_quote_escape(&config.display().to_string());
    format!(
        "-WindowStyle Hidden -NoProfile -Command \"$log = Join-Path $env:LOCALAPPDATA 'navi\\navi.log'; New-Item -ItemType Directory -Force -Path (Split-Path $log) | Out-Null; if ((Test-Path $log) -and ((Get-Item $log).Length -gt {cap})) {{ Move-Item -Force $log ($log + '.1') }}; & '{exe}' run --config '{config}' *>> $log\"",
        cap = WINDOWS_LOG_MAX_BYTES,
    )
}

/// A Task Scheduler XML definition for the logon task. Registered via `schtasks
/// /XML`, which — unlike `/TR` — imposes no 261-char command limit, so navi's hidden
/// PowerShell log-wrapper plus long install/config paths can't overflow it (#125).
fn task_xml(exe: &str, config: &Path) -> String {
    let args = xml_escape(&ps_run_arguments(exe, config));
    format!(
        r#"<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <Triggers>
    <LogonTrigger>
      <Enabled>true</Enabled>
    </LogonTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <LogonType>InteractiveToken</LogonType>
      <RunLevel>LeastPrivilege</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <StartWhenAvailable>true</StartWhenAvailable>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <Enabled>true</Enabled>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>powershell</Command>
      <Arguments>{args}</Arguments>
    </Exec>
  </Actions>
</Task>
"#
    )
}

/// Encode as UTF-16LE with a BOM, matching the XML declaration — schtasks rejects a
/// task file whose bytes don't match its declared encoding.
fn utf16le_with_bom(s: &str) -> Vec<u8> {
    let mut bytes = vec![0xFF, 0xFE];
    for unit in s.encode_utf16() {
        bytes.extend_from_slice(&unit.to_le_bytes());
    }
    bytes
}

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

fn current_exe_string() -> Result<String> {
    let path = env::current_exe().context("cannot determine the navi binary path")?;
    Ok(path.to_string_lossy().into_owned())
}

fn home_dir() -> Result<PathBuf> {
    env::var_os("HOME")
        .map(PathBuf::from)
        .context("cannot locate your home directory; set HOME")
}

/// The token env file lives next to the config so the two travel together.
fn env_file_path(config: &Path) -> PathBuf {
    config
        .parent()
        .unwrap_or_else(|| Path::new("."))
        .join("navi.env")
}

/// Create a commented, 0600 env-file template if one is not already there.
fn ensure_env_file(path: &Path) -> Result<()> {
    if path.exists() {
        return Ok(());
    }
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }
    fs::write(path, ENV_TEMPLATE).with_context(|| format!("failed to write {}", path.display()))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(path, fs::Permissions::from_mode(0o600))
            .with_context(|| format!("failed to chmod 600 {}", path.display()))?;
    }
    Ok(())
}

const ENV_TEMPLATE: &str = "# navi service environment (chmod 600). One KEY=value per line.\n\
    # Fill in tokens for the sources and destinations you enabled in config.toml.\n\
    NAVI_GITHUB_TOKEN=\n\
    NAVI_SLACK_TOKEN=\n\
    # NAVI_GITLAB_TOKEN=\n\
    # NAVI_GITEA_TOKEN=\n\
    # NAVI_DISCORD_TOKEN=\n\
    # NAVI_EMAIL_PASSWORD=\n";

fn print_env_hint(env_file: &Path, restart_cmd: &str) {
    println!(
        "put your tokens in {} (already chmod 600):",
        env_file.display()
    );
    println!("  NAVI_GITHUB_TOKEN=ghp_...");
    println!("  NAVI_SLACK_TOKEN=xoxb-...");
    println!("then restart the service:  {restart_cmd}");
}

/// Prompt for confirmation, mirroring `setup`: only ask at a real terminal;
/// non-interactive without `--yes` skips cleanly rather than reading EOF as "no".
fn approve(yes: bool, message: &str) -> Result<bool> {
    if yes {
        return Ok(true);
    }
    if !std::io::stdin().is_terminal() {
        println!("non-interactive; re-run with --yes to install without a prompt");
        return Ok(false);
    }
    let proceed = confirm(message)?;
    if !proceed {
        println!("cancelled");
    }
    Ok(proceed)
}

fn run(cmd: &mut Command) -> Result<()> {
    let program = cmd.get_program().to_string_lossy().into_owned();
    let status = cmd
        .status()
        .with_context(|| format!("failed to run {program}"))?;
    if !status.success() {
        bail!("{program} exited with {status}");
    }
    Ok(())
}

/// Run a command and return its trimmed stdout, or `None` if it could not run.
fn capture(cmd: &mut Command) -> Option<String> {
    let output = cmd.output().ok()?;
    let text = String::from_utf8_lossy(&output.stdout).trim().to_owned();
    (!text.is_empty()).then_some(text)
}

fn xml_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

/// Double single quotes for safe embedding in a PowerShell single-quoted string.
fn ps_single_quote_escape(s: &str) -> String {
    s.replace('\'', "''")
}

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

    #[test]
    fn systemd_unit_wires_exe_config_and_env_file() {
        let unit = systemd_unit(
            "/home/me/.cargo/bin/navi",
            Path::new("/home/me/.config/navi/config.toml"),
            Path::new("/home/me/.config/navi/navi.env"),
        );
        assert!(unit
            .contains("ExecStart=\"/home/me/.cargo/bin/navi\" run --config \"/home/me/.config/navi/config.toml\""));
        assert!(unit.contains("EnvironmentFile=-/home/me/.config/navi/navi.env"));
        assert!(unit.contains("WantedBy=default.target"));
    }

    #[test]
    fn launchd_plist_sources_env_then_execs_navi() {
        let plist = launchd_plist(
            "/usr/local/bin/navi",
            Path::new("/Users/me/.config/navi/config.toml"),
            Path::new("/Users/me/.config/navi/navi.env"),
            Path::new("/Users/me/Library/Logs/navi.log"),
        );
        assert!(plist.contains("<string>dev.navi.navi</string>"));
        assert!(plist.contains(". \"/Users/me/.config/navi/navi.env\""));
        assert!(plist.contains("exec \"/usr/local/bin/navi\" run"));
        assert!(plist.contains("/Users/me/Library/Logs/navi.log"));
    }

    #[test]
    fn ps_run_arguments_escape_single_quotes_in_paths() {
        let args = ps_run_arguments(
            "C:\\Users\\O'Brien\\navi.exe",
            Path::new("C:\\Users\\O'Brien\\config.toml"),
        );
        // Doubled quotes keep the path inside its single-quoted PowerShell string.
        assert!(args.contains("'C:\\Users\\O''Brien\\navi.exe'"));
        assert!(args.contains("'C:\\Users\\O''Brien\\config.toml'"));
    }

    #[test]
    fn task_xml_embeds_the_hidden_logon_action() {
        let xml = task_xml(
            "C:\\navi.exe",
            Path::new("C:\\Users\\me\\navi\\config.toml"),
        );
        // A logon-triggered, least-privilege task running navi through hidden PowerShell.
        assert!(xml.contains("<LogonTrigger>"));
        assert!(xml.contains("<RunLevel>LeastPrivilege</RunLevel>"));
        assert!(xml.contains("<Command>powershell</Command>"));
        assert!(xml.contains("WindowStyle Hidden"));
        assert!(xml.contains("C:\\navi.exe"));
        assert!(xml.contains("navi.log"));
        assert!(
            xml.contains("$env:LOCALAPPDATA"),
            "log must live under LOCALAPPDATA"
        );
        assert!(xml.contains(&WINDOWS_LOG_MAX_BYTES.to_string()));
        // The `*>>` redirect's angle brackets are XML-escaped, not raw.
        assert!(
            xml.contains("*&gt;&gt;"),
            "redirect must be XML-escaped: {xml}"
        );
        assert!(
            !xml.contains("*>>"),
            "no unescaped redirect should leak into the XML"
        );
    }

    #[test]
    fn utf16le_with_bom_starts_with_the_bom() {
        let bytes = utf16le_with_bom("Ab");
        assert_eq!(&bytes[..2], &[0xFF, 0xFE], "UTF-16LE BOM");
        assert_eq!(&bytes[2..], &[b'A', 0x00, b'b', 0x00]);
    }

    #[test]
    fn env_template_is_chmod_600_and_not_overwritten() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("navi.env");
        ensure_env_file(&path).unwrap();
        assert!(path.exists());
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = fs::metadata(&path).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o600);
        }
        // A second call must not clobber user-entered tokens.
        fs::write(&path, "NAVI_GITHUB_TOKEN=secret\n").unwrap();
        ensure_env_file(&path).unwrap();
        assert_eq!(
            fs::read_to_string(&path).unwrap(),
            "NAVI_GITHUB_TOKEN=secret\n"
        );
    }

    #[test]
    fn xml_escape_handles_ampersand_and_angles() {
        assert_eq!(xml_escape("a & b < c > d"), "a &amp; b &lt; c &gt; d");
    }

    #[test]
    fn exec_program_extracts_the_binary_path() {
        // Our generated form: quoted path + args.
        assert_eq!(
            exec_program("\"/home/me/.local/bin/navi\" run --config \"/home/me/c.toml\""),
            "/home/me/.local/bin/navi"
        );
        // The old hand-copied template form: bare path + args.
        assert_eq!(
            exec_program("/home/me/.cargo/bin/navi run"),
            "/home/me/.cargo/bin/navi"
        );
    }
}