pacsea 0.8.2

A fast, friendly TUI for browsing and installing Arch and AUR packages with built-in news and security scanning
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
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
//! SSH setup workflow helpers for AUR voting.

use std::fs;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Arc, Mutex};

/// Fixed host used by AUR SSH voting.
const AUR_HOST: &str = "aur.archlinux.org";
/// Fixed SSH key file name for the guided setup flow.
const AUR_KEY_NAME: &str = "aur_key";
/// Login URL shown in the setup flow.
pub const AUR_ACCOUNT_URL: &str = "https://aur.archlinux.org/login";

/// What: Extract the first OpenSSH public key line from setup status lines.
///
/// Inputs:
/// - `status_lines`: Lines produced by `run_aur_ssh_setup` / validation (may include labels and hints).
///
/// Output:
/// - Trimmed key line (for example `ssh-ed25519 AAAA... comment`) when found.
///
/// Details:
/// - Matches lines whose trimmed text starts with `ssh-` (covers `ssh-ed25519`, `ssh-rsa`, etc.).
#[must_use]
pub fn ssh_public_key_line_from_status_lines(status_lines: &[String]) -> Option<String> {
    status_lines.iter().find_map(|line| {
        let trimmed = line.trim();
        trimmed.starts_with("ssh-").then(|| trimmed.to_string())
    })
}

/// What: Copy the first OpenSSH public key line from setup status lines to the clipboard.
///
/// Inputs:
/// - `status_lines`: Modal status lines that may include a line starting with `ssh-`.
///
/// Output:
/// - `None` when no public key line is present.
/// - `Some(Ok(()))` when `wl-copy` or `xclip` accepted the key text.
/// - `Some(Err(message))` when a key line exists but clipboard copy failed.
///
/// Details:
/// - Delegates to `crate::util::clipboard::copy_plain_text_to_clipboard` (no PKGBUILD suffix).
#[must_use]
pub fn try_copy_aur_ssh_public_key_from_status_lines(
    status_lines: &[String],
) -> Option<Result<(), String>> {
    let key_line = ssh_public_key_line_from_status_lines(status_lines)?;
    Some(crate::util::clipboard::copy_plain_text_to_clipboard(
        &key_line,
    ))
}

/// What: Check whether `openssh` is installed on the system.
///
/// Inputs: None.
///
/// Output:
/// - `true` when `openssh` is detected as installed.
///
/// Details:
/// - Uses Pacsea installed-package index (`openssh` package name).
#[must_use]
pub fn is_openssh_installed() -> bool {
    #[cfg(test)]
    if let Ok(v) = std::env::var("PACSEA_TEST_OPENSSH_INSTALLED") {
        return v == "1";
    }
    crate::index::is_installed("openssh")
}

/// What: Workflow result for attempting SSH setup actions.
///
/// Inputs:
/// - Produced by `run_aur_ssh_setup`.
///
/// Output:
/// - Either a completed report or an overwrite-confirmation request.
///
/// Details:
/// - `NeedsOverwrite` includes the currently detected host block and progress lines.
pub enum AurSshSetupResult {
    /// Setup finished (success or failure details are in `report.success` + `report.lines`).
    Completed(AurSshSetupReport),
    /// Existing host block requires explicit user overwrite confirmation.
    NeedsOverwrite {
        /// Existing host block text from `~/.ssh/config`.
        existing_block: String,
        /// Status lines generated before the overwrite decision point.
        lines: Vec<String>,
    },
}

/// What: Final setup report for modal rendering.
///
/// Inputs:
/// - Built by `run_aur_ssh_setup`.
///
/// Output:
/// - `success` flag and human-readable status lines.
pub struct AurSshSetupReport {
    /// Whether the full workflow completed successfully.
    pub success: bool,
    /// Human-readable step/result lines for UI display.
    pub lines: Vec<String>,
}

/// What: Detect whether AUR SSH setup appears configured locally.
///
/// Inputs: None.
///
/// Output:
/// - `true` when key exists and `~/.ssh/config` has required AUR host directives.
///
/// Details:
/// - This check is local-only and does not validate remote SSH auth/network.
#[must_use]
pub fn is_aur_ssh_setup_configured() -> bool {
    let Some(home) = home_dir() else {
        return false;
    };
    let ssh_dir = home.join(".ssh");
    let key_path = ssh_dir.join(AUR_KEY_NAME);
    if !key_path.exists() {
        return false;
    }
    let config_path = ssh_dir.join("config");
    let Ok(content) = fs::read_to_string(config_path) else {
        return false;
    };
    find_host_block(&content, AUR_HOST)
        .is_some_and(|(_, _, block)| block_has_required_directives(&block))
}

/// What: Run the guided AUR SSH setup flow.
///
/// Inputs:
/// - `overwrite_existing_host`: Whether to overwrite a conflicting existing host block.
///
/// Output:
/// - `AurSshSetupResult` with either completion report or explicit overwrite request.
///
/// Details:
/// - Creates `~/.ssh` if missing.
/// - Generates `~/.ssh/aur_key` via `ssh-keygen` if not present.
/// - Writes/updates minimal `Host aur.archlinux.org` block.
#[must_use]
pub fn run_aur_ssh_setup(overwrite_existing_host: bool) -> AurSshSetupResult {
    let mut lines = Vec::new();
    let Some(home) = home_dir() else {
        return AurSshSetupResult::Completed(AurSshSetupReport {
            success: false,
            lines: vec![setup_failure_line(
                "home",
                "could not resolve your home directory (HOME may be unset in this session)",
            )],
        });
    };
    let ssh_dir = home.join(".ssh");
    if let Err(err) = fs::create_dir_all(&ssh_dir) {
        return AurSshSetupResult::Completed(AurSshSetupReport {
            success: false,
            lines: vec![setup_failure_line(
                "directory creation",
                format!("could not create '{}': {err}", ssh_dir.display()),
            )],
        });
    }
    lines.push(format!("SSH directory ready: '{}'", ssh_dir.display()));
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Err(err) = fs::set_permissions(&ssh_dir, fs::Permissions::from_mode(0o700)) {
            lines.push(format!(
                "Warning: could not set '{}' permissions to 700: {err}",
                ssh_dir.display()
            ));
        }
    }
    let known_hosts_path = match ensure_known_hosts_file_exists(&ssh_dir, &mut lines) {
        Ok(path) => path,
        Err(err) => {
            return AurSshSetupResult::Completed(AurSshSetupReport {
                success: false,
                lines: vec![setup_failure_line("known_hosts", err)],
            });
        }
    };
    maybe_seed_known_hosts_with_aur_entry(&known_hosts_path, &mut lines);

    let key_path = ssh_dir.join(AUR_KEY_NAME);
    if key_path.exists() {
        lines.push(format!("Key exists: '{}'", key_path.display()));
    } else {
        let output = Command::new("ssh-keygen")
            .args(["-t", "ed25519", "-f"])
            .arg(&key_path)
            .args(["-N", ""])
            .output();
        match output {
            Ok(out) if out.status.success() => {
                lines.push(format!("Created key pair: '{}'", key_path.display()));
            }
            Ok(out) => {
                let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
                lines.push(format!(
                    "Failed [keygen]: ssh-keygen exited with code {}: {}",
                    out.status.code().unwrap_or(-1),
                    if stderr.is_empty() {
                        "no stderr output".to_string()
                    } else {
                        stderr
                    }
                ));
                return AurSshSetupResult::Completed(AurSshSetupReport {
                    success: false,
                    lines,
                });
            }
            Err(err) => {
                lines.push(setup_failure_line(
                    "keygen",
                    format!("could not run ssh-keygen: {err}"),
                ));
                return AurSshSetupResult::Completed(AurSshSetupReport {
                    success: false,
                    lines,
                });
            }
        }
    }

    let config_path = ssh_dir.join("config");
    match write_or_update_aur_host_config(&config_path, overwrite_existing_host, &mut lines) {
        Ok(Some(existing_block)) => {
            return AurSshSetupResult::NeedsOverwrite {
                existing_block,
                lines,
            };
        }
        Ok(None) => {}
        Err(err) => {
            lines.push(setup_failure_line(
                "config update",
                format!("could not update '{}': {err}", config_path.display()),
            ));
            return AurSshSetupResult::Completed(AurSshSetupReport {
                success: false,
                lines,
            });
        }
    }

    let pub_key_path = key_path.with_extension("pub");
    match fs::read_to_string(&pub_key_path) {
        Ok(pub_key) => {
            let trimmed = pub_key.trim();
            if trimmed.is_empty() {
                lines.push(
                    "Warning: public key file is empty. Re-run setup or regenerate key."
                        .to_string(),
                );
            } else {
                lines.push(format!(
                    "Public key file: '{}' (copy this into your AUR account).",
                    pub_key_path.display()
                ));
                lines.push(trimmed.to_string());
            }
        }
        Err(err) => {
            lines.push(format!(
                "Warning: could not read public key '{}': {err}",
                pub_key_path.display()
            ));
        }
    }
    lines.push(format!(
        "Next step: open {AUR_ACCOUNT_URL} and paste the public key."
    ));
    AurSshSetupResult::Completed(AurSshSetupReport {
        success: true,
        lines,
    })
}

/// What: Ensure the `~/.ssh/known_hosts` file exists and has restrictive permissions.
///
/// Inputs:
/// - `ssh_dir`: Existing `~/.ssh` directory path.
/// - `lines`: Status lines accumulator for UI diagnostics.
///
/// Output:
/// - `Ok(path)` with `known_hosts` path when ready.
/// - `Err(reason)` when file creation/opening fails.
fn ensure_known_hosts_file_exists(
    ssh_dir: &Path,
    lines: &mut Vec<String>,
) -> Result<PathBuf, String> {
    let known_hosts_path = ssh_dir.join("known_hosts");
    if known_hosts_path.exists() {
        lines.push(format!(
            "known_hosts file ready: '{}'",
            known_hosts_path.display()
        ));
    } else {
        OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(false)
            .open(&known_hosts_path)
            .map_err(|err| format!("could not create '{}': {err}", known_hosts_path.display()))?;
        lines.push(format!(
            "Created known_hosts file: '{}'",
            known_hosts_path.display()
        ));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Err(err) = fs::set_permissions(&known_hosts_path, fs::Permissions::from_mode(0o600))
        {
            lines.push(format!(
                "Warning: could not set '{}' permissions to 600: {err}",
                known_hosts_path.display()
            ));
        }
    }
    Ok(known_hosts_path)
}

/// What: Try to add `aur.archlinux.org` host key to `known_hosts`.
///
/// Inputs:
/// - `known_hosts_path`: Absolute `known_hosts` file path.
/// - `lines`: Status lines accumulator for UI diagnostics.
///
/// Output:
/// - None (best-effort, non-fatal).
fn maybe_seed_known_hosts_with_aur_entry(known_hosts_path: &Path, lines: &mut Vec<String>) {
    let content = fs::read_to_string(known_hosts_path).unwrap_or_default();
    if content.contains(AUR_HOST) {
        lines.push("known_hosts already contains aur.archlinux.org entry.".to_string());
        return;
    }
    let output = Command::new("ssh-keyscan").args(["-H", AUR_HOST]).output();
    match output {
        Ok(out) if out.status.success() && !out.stdout.is_empty() => {
            match OpenOptions::new().append(true).open(known_hosts_path) {
                Ok(mut file) => {
                    if let Err(err) = file.write_all(&out.stdout) {
                        lines.push(format!(
                            "Warning: failed to append AUR host key to '{}': {err}",
                            known_hosts_path.display()
                        ));
                    } else {
                        lines.push("Added aur.archlinux.org host key to known_hosts.".to_string());
                    }
                }
                Err(err) => {
                    lines.push(format!(
                        "Warning: failed to open '{}' for host key append: {err}",
                        known_hosts_path.display()
                    ));
                }
            }
        }
        Ok(out) => {
            let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
            lines.push(format!(
                "Warning: could not fetch AUR host key via ssh-keyscan (exit {}): {}",
                out.status.code().unwrap_or(-1),
                if stderr.is_empty() {
                    "no stderr output".to_string()
                } else {
                    stderr
                }
            ));
        }
        Err(err) => {
            lines.push(format!(
                "Warning: ssh-keyscan unavailable for known_hosts seeding: {err}"
            ));
        }
    }
}

/// What: Validate AUR SSH connectivity after the user applies the public key.
///
/// Inputs:
/// - `ssh_command`: SSH binary path or name used for validation command execution.
///
/// Output:
/// - `AurSshSetupReport` with success flag and validation-specific status lines.
#[must_use]
pub fn validate_aur_ssh_setup_connection(ssh_command: &str) -> AurSshSetupReport {
    let Some(home) = home_dir() else {
        return AurSshSetupReport {
            success: false,
            lines: vec![setup_failure_line(
                "home",
                "could not resolve your home directory (HOME may be unset in this session)",
            )],
        };
    };
    let key_path = home.join(".ssh").join(AUR_KEY_NAME);
    let validation = Command::new(ssh_command)
        .args(["-o", "BatchMode=yes", "-o", "ConnectTimeout=10"])
        .arg("aur@aur.archlinux.org")
        .arg("help")
        .output();
    match validation {
        Ok(out) if out.status.success() => AurSshSetupReport {
            success: true,
            lines: vec!["Validation OK: 'ssh aur@aur.archlinux.org help' succeeded.".to_string()],
        },
        Ok(out) => {
            let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
            let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
            let detail = if stderr.is_empty() { stdout } else { stderr };
            let mut lines = Vec::new();
            lines.push(format!(
                "Failed [connection check]: ssh validation exited with code {}: {}",
                out.status.code().unwrap_or(-1),
                if detail.is_empty() {
                    "no output".to_string()
                } else {
                    detail
                }
            ));
            lines.push(format!(
                "Next step: upload public key '{}' to {}",
                key_path.with_extension("pub").display(),
                AUR_ACCOUNT_URL
            ));
            AurSshSetupReport {
                success: false,
                lines,
            }
        }
        Err(err) => AurSshSetupReport {
            success: false,
            lines: vec![setup_failure_line(
                "connection check",
                format!("could not run ssh validation command '{ssh_command}': {err}"),
            )],
        },
    }
}

/// What: Build a standardized setup failure line with stage context.
fn setup_failure_line(stage: &str, detail: impl AsRef<str>) -> String {
    format!("Failed [{stage}]: {}", detail.as_ref())
}

/// What: Spawn a background SSH validation check for AUR endpoint readiness.
///
/// Inputs:
/// - `ssh_command`: SSH binary path or name used for the endpoint check.
///
/// Output:
/// - Shared handle containing `Some(true/false)` when finished, or `None` while running.
///
/// Details:
/// - Runs `{ssh_command} -o BatchMode=yes -o ConnectTimeout=8 aur@aur.archlinux.org help`
///   on a worker thread.
#[must_use]
pub fn spawn_aur_ssh_help_check(ssh_command: String) -> Arc<Mutex<Option<bool>>> {
    let result = Arc::new(Mutex::new(None));
    let result_clone = Arc::clone(&result);
    std::thread::spawn(move || {
        let ok = Command::new(&ssh_command)
            .args(["-o", "BatchMode=yes", "-o", "ConnectTimeout=8"])
            .arg("aur@aur.archlinux.org")
            .arg("help")
            .output()
            .is_ok_and(|out| out.status.success());
        if let Ok(mut slot) = result_clone.lock() {
            *slot = Some(ok);
        }
    });
    result
}

/// What: Resolve current user's home directory.
fn home_dir() -> Option<PathBuf> {
    std::env::var("HOME")
        .ok()
        .filter(|v| !v.trim().is_empty())
        .map(PathBuf::from)
        .or_else(resolve_home_dir_unix_passwd)
}

/// What: Resolve home dir via passwd database on Unix.
///
/// Inputs: None.
///
/// Output:
/// - `Some(path)` when current uid has a valid passwd home entry.
///
/// Details:
/// - Acts as fallback when `HOME` is unset/empty in the app process environment.
#[cfg(unix)]
fn resolve_home_dir_unix_passwd() -> Option<PathBuf> {
    use nix::unistd::{Uid, User};

    let uid = Uid::current();
    User::from_uid(uid)
        .ok()
        .flatten()
        .and_then(|user| (!user.dir.as_os_str().is_empty()).then_some(user.dir))
}

/// What: Non-Unix fallback for home-dir resolution.
///
/// Inputs: None.
///
/// Output:
/// - Always `None` on non-Unix targets.
///
/// Details:
/// - Placeholder so `home_dir()` can call a single cross-platform fallback symbol.
#[cfg(not(unix))]
fn resolve_home_dir_unix_passwd() -> Option<PathBuf> {
    None
}

/// What: Build the target host block text for AUR SSH voting.
fn desired_aur_host_block() -> String {
    "Host aur.archlinux.org\n  User aur\n  IdentityFile ~/.ssh/aur_key\n  IdentitiesOnly yes\n"
        .to_string()
}

/// What: Find one host block range by host token.
///
/// Output:
/// - `(start_byte, end_byte, block_text)` when found.
fn find_host_block(content: &str, host: &str) -> Option<(usize, usize, String)> {
    let mut entries: Vec<(usize, &str)> = Vec::new();
    let mut start = 0usize;
    for line in content.lines() {
        entries.push((start, line));
        start = start.saturating_add(line.len()).saturating_add(1);
    }
    let mut block_start: Option<usize> = None;
    let mut end = content.len();
    for (line_start, line) in entries {
        let trimmed = line.trim();
        if !trimmed.starts_with("Host ") {
            continue;
        }
        if block_start.is_none() {
            let hosts = trimmed.trim_start_matches("Host ").split_whitespace();
            if hosts.into_iter().any(|entry| entry == host) {
                block_start = Some(line_start);
            }
            continue;
        }
        end = line_start;
        break;
    }
    let start = block_start?;
    Some((start, end, content[start..end].trim_end().to_string()))
}

/// What: Determine whether a host block contains required directives.
fn block_has_required_directives(block: &str) -> bool {
    let mut user_ok = false;
    let mut id_ok = false;
    let mut only_ok = false;
    for line in block.lines() {
        let trimmed = line.trim();
        if trimmed.eq_ignore_ascii_case("User aur") {
            user_ok = true;
        } else if trimmed.eq_ignore_ascii_case("IdentityFile ~/.ssh/aur_key") {
            id_ok = true;
        } else if trimmed.eq_ignore_ascii_case("IdentitiesOnly yes") {
            only_ok = true;
        }
    }
    user_ok && id_ok && only_ok
}

/// What: Update `~/.ssh/config` with desired host block.
///
/// Output:
/// - `Ok(Some(existing_block))` when overwrite confirmation is required.
/// - `Ok(None)` when write/update succeeded or file already compliant.
fn write_or_update_aur_host_config(
    config_path: &Path,
    overwrite_existing_host: bool,
    lines: &mut Vec<String>,
) -> Result<Option<String>, String> {
    let desired = desired_aur_host_block();
    let mut content = fs::read_to_string(config_path).unwrap_or_default();
    if let Some((start, end, existing)) = find_host_block(&content, AUR_HOST) {
        if block_has_required_directives(&existing) {
            lines.push(format!(
                "SSH config already contains required '{AUR_HOST}'."
            ));
            return Ok(None);
        }
        if !overwrite_existing_host {
            lines.push(format!(
                "Existing '{AUR_HOST}' block detected. Confirmation required to overwrite."
            ));
            return Ok(Some(existing));
        }
        content.replace_range(start..end, &desired);
        lines.push(format!("Overwrote existing '{AUR_HOST}' host block."));
    } else {
        if !content.is_empty() && !content.ends_with('\n') {
            content.push('\n');
        }
        if !content.is_empty() {
            content.push('\n');
        }
        content.push_str(&desired);
        lines.push(format!("Added new '{AUR_HOST}' host block."));
    }
    fs::write(config_path, content).map_err(|e| e.to_string())?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Err(err) = fs::set_permissions(config_path, fs::Permissions::from_mode(0o600)) {
            lines.push(format!(
                "Warning: could not set '{}' permissions to 600: {err}",
                config_path.display()
            ));
        }
    }
    Ok(None)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn temp_config_path(name: &str) -> PathBuf {
        let stamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_or(0, |d| d.as_nanos());
        std::env::temp_dir().join(format!(
            "pacsea_{name}_{}_{}.conf",
            std::process::id(),
            stamp
        ))
    }

    #[test]
    fn block_directives_detected() {
        let block = "Host aur.archlinux.org\n  User aur\n  IdentityFile ~/.ssh/aur_key\n  IdentitiesOnly yes\n";
        assert!(block_has_required_directives(block));
    }

    #[test]
    fn block_directives_missing_detected() {
        let block = "Host aur.archlinux.org\n  User aur\n  IdentityFile ~/.ssh/id_ed25519\n";
        assert!(!block_has_required_directives(block));
    }

    #[test]
    fn find_host_block_returns_range() {
        let content = "Host github.com\n  User git\n\nHost aur.archlinux.org\n  User aur\n";
        let found = find_host_block(content, "aur.archlinux.org")
            .expect("expected aur host block to be found");
        assert!(found.2.contains("Host aur.archlinux.org"));
    }

    #[test]
    fn write_or_update_requests_overwrite_for_conflicting_block() {
        let path = temp_config_path("ssh_setup_conflict");
        let original = "Host aur.archlinux.org\n  User aur\n  IdentityFile ~/.ssh/id_ed25519\n";
        fs::write(&path, original).expect("should write temp config");
        let mut lines = Vec::new();
        let result =
            write_or_update_aur_host_config(&path, false, &mut lines).expect("should not error");
        assert!(
            result.is_some(),
            "conflicting block should request overwrite"
        );
        let _ = fs::remove_file(path);
    }

    #[test]
    fn write_or_update_writes_expected_block_when_missing() {
        let path = temp_config_path("ssh_setup_missing");
        let _ = fs::remove_file(&path);
        let mut lines = Vec::new();
        let result =
            write_or_update_aur_host_config(&path, false, &mut lines).expect("should not error");
        assert!(result.is_none(), "missing block should be written directly");
        let body = fs::read_to_string(&path).expect("config should be created");
        assert!(body.contains("Host aur.archlinux.org"));
        assert!(body.contains("IdentityFile ~/.ssh/aur_key"));
        let _ = fs::remove_file(path);
    }

    #[test]
    fn openssh_check_honors_test_override() {
        unsafe {
            std::env::set_var("PACSEA_TEST_OPENSSH_INSTALLED", "1");
        }
        assert!(is_openssh_installed());
        unsafe {
            std::env::set_var("PACSEA_TEST_OPENSSH_INSTALLED", "0");
        }
        assert!(!is_openssh_installed());
        unsafe {
            std::env::remove_var("PACSEA_TEST_OPENSSH_INSTALLED");
        }
    }

    #[test]
    fn setup_failure_line_includes_stage_and_detail() {
        let line = setup_failure_line("connection check", "network timeout");
        assert_eq!(
            line,
            "Failed [connection check]: network timeout".to_string()
        );
    }

    #[test]
    fn ssh_public_key_line_from_status_finds_first_key_line() {
        let lines = vec![
            "Key exists: '/home/u/.ssh/aur_key'".to_string(),
            "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIABCD user@host".to_string(),
            "Next step: open https://example.test/login".to_string(),
        ];
        assert_eq!(
            ssh_public_key_line_from_status_lines(&lines).as_deref(),
            Some("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIABCD user@host")
        );
    }

    #[test]
    fn ensure_known_hosts_file_exists_creates_missing_file() {
        let stamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_or(0, |d| d.as_nanos());
        let ssh_dir = std::env::temp_dir().join(format!(
            "pacsea_ssh_known_hosts_{}_{}",
            std::process::id(),
            stamp
        ));
        fs::create_dir_all(&ssh_dir).expect("should create temp ssh dir");
        let mut lines = Vec::new();
        let path = ensure_known_hosts_file_exists(&ssh_dir, &mut lines)
            .expect("should create known_hosts");
        assert!(path.exists(), "known_hosts file should exist");
        assert!(
            lines
                .iter()
                .any(|line| line.contains("Created known_hosts file")),
            "status lines should mention known_hosts creation"
        );
        let _ = fs::remove_file(path);
        let _ = fs::remove_dir(ssh_dir);
    }
}