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
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
//! Privilege escalation abstraction for sudo/doas support.
//!
//! # doas capability spike (Phase 0)
//!
//! **Target package:** `opendoas` (Arch: `extra/opendoas`)
//! **Minimum supported behavior:** `OpenDoas` as packaged in Arch Linux repos.
//!
//! ## Supported patterns
//!
//! | Pattern | sudo | doas |
//! |---|---|---|
//! | Non-interactive check | `sudo -n true` | `doas -n true` |
//! | Direct command execution | `sudo <cmd>` | `doas <cmd>` |
//! | Passwordless execution | sudoers `NOPASSWD` | `permit nopass` in `/etc/doas.conf` |
//! | Password via stdin | `sudo -S` reads stdin | **NOT supported** |
//! | Credential refresh | `sudo -v` | **NOT supported** |
//! | Credential invalidation | `sudo -k` | **NOT supported** |
//! | Askpass env var | `SUDO_ASKPASS` | **NOT supported** |
//!
//! ## Implications for Pacsea
//!
//! - When doas requires a password, it prompts via its own terminal interaction.
//! - The in-app password modal **cannot** be used with doas (no stdin pipe support).
//! - Pacsea skips the password modal for doas and lets the spawned terminal handle prompting.
//! - Credential warm-up (`sudo -S -v`) is unavailable for doas.
//! - `doas -n true` works identically to `sudo -n true` for passwordless detection.

use std::fmt;
use std::process::Command;

/// What: Privilege escalation tool supported by Pacsea.
///
/// Inputs: None (enum variant selection).
///
/// Output: Identifies which privilege tool to invoke.
///
/// Details:
/// - `Sudo` uses the standard sudo binary with full feature support
///   (stdin password, credential caching, askpass).
/// - `Doas` uses the `OpenDoas` binary with limited feature support
///   (no stdin password, no credential caching).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PrivilegeTool {
    /// Standard sudo — full feature support.
    Sudo,
    /// `OpenDoas` — limited feature support (no stdin password pipe, no credential caching).
    Doas,
}

/// What: User-configured privilege tool selection mode parsed from `settings.conf`.
///
/// Inputs: None (enum variant selection).
///
/// Output: Controls how Pacsea selects the privilege escalation tool.
///
/// Details:
/// - `Auto` (default): prefer doas if available on `$PATH`, fall back to sudo.
/// - `Sudo`: always use sudo; fail with actionable error if unavailable.
/// - `Doas`: always use doas; fail with actionable error if unavailable.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PrivilegeMode {
    /// Auto-detect: prefer doas if available, fall back to sudo.
    #[default]
    Auto,
    /// Always use sudo.
    Sudo,
    /// Always use doas.
    Doas,
}

/// What: Capability flags describing which features a privilege tool supports.
///
/// Inputs: None (populated per tool via [`PrivilegeTool::capabilities`]).
///
/// Output: Boolean flags for each optional capability.
///
/// Details:
/// - sudo supports all capabilities.
/// - doas supports none of these optional capabilities.
/// - Used to route behavior: e.g. skip password modal when stdin pipe is unsupported.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[allow(clippy::struct_excessive_bools)]
pub struct PrivilegeCapabilities {
    /// Tool supports reading password from stdin (`sudo -S`).
    pub supports_stdin_password: bool,
    /// Tool supports credential validation/refresh without running a command (`sudo -v`).
    pub supports_credential_refresh: bool,
    /// Tool supports credential invalidation (`sudo -k`).
    pub supports_credential_invalidation: bool,
    /// Tool supports the `ASKPASS` environment variable (`SUDO_ASKPASS`).
    pub supports_askpass: bool,
}

// ---------------------------------------------------------------------------
// PrivilegeTool implementation
// ---------------------------------------------------------------------------

impl PrivilegeTool {
    /// What: Return the shell binary name for this tool.
    ///
    /// Inputs: None.
    ///
    /// Output: `"sudo"` or `"doas"`.
    ///
    /// Details: Used in command construction and `which` lookups.
    #[must_use]
    pub const fn binary_name(self) -> &'static str {
        match self {
            Self::Sudo => "sudo",
            Self::Doas => "doas",
        }
    }

    /// What: Return the capability flags for this tool.
    ///
    /// Inputs: None.
    ///
    /// Output: [`PrivilegeCapabilities`] with tool-specific flags.
    ///
    /// Details:
    /// - sudo: all capabilities enabled.
    /// - doas: all capabilities disabled (see module-level docs for rationale).
    #[must_use]
    pub const fn capabilities(self) -> PrivilegeCapabilities {
        match self {
            Self::Sudo => PrivilegeCapabilities {
                supports_stdin_password: true,
                supports_credential_refresh: true,
                supports_credential_invalidation: true,
                supports_askpass: true,
            },
            Self::Doas => PrivilegeCapabilities {
                supports_stdin_password: false,
                supports_credential_refresh: false,
                supports_credential_invalidation: false,
                supports_askpass: false,
            },
        }
    }

    /// What: Check whether this tool's binary exists on `$PATH`.
    ///
    /// Inputs: None.
    ///
    /// Output: `true` if the binary is found.
    ///
    /// Details:
    /// - In integration test context (`PACSEA_INTEGRATION_TEST=1`), honors
    ///   `PACSEA_TEST_PRIVILEGE_AVAILABLE` (comma-separated list, or `"none"`).
    /// - Production: delegates to `which::which`.
    #[must_use]
    pub fn is_available(self) -> bool {
        if is_integration_test_context()
            && let Ok(val) = std::env::var("PACSEA_TEST_PRIVILEGE_AVAILABLE")
        {
            if val == "none" {
                return false;
            }
            return val.split(',').any(|t| t.trim() == self.binary_name());
        }
        which::which(self.binary_name()).is_ok()
    }

    /// What: Check whether passwordless privilege escalation is available.
    ///
    /// Inputs: None.
    ///
    /// Output: `Ok(true)` if non-interactive execution succeeds, `Err` if the check itself fails.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the tool binary cannot be executed (e.g. not installed).
    ///
    /// Details:
    /// - Runs `<tool> -n true` (`-n` = non-interactive, `true` = no-op command).
    /// - Both sudo and doas support the `-n` flag.
    /// - In integration test context, honors `PACSEA_TEST_SUDO_PASSWORDLESS`.
    pub fn check_passwordless(self) -> Result<bool, String> {
        if is_integration_test_context()
            && let Ok(val) = std::env::var("PACSEA_TEST_SUDO_PASSWORDLESS")
        {
            tracing::debug!(
                tool = self.binary_name(),
                val = %val,
                "Using test override for passwordless check"
            );
            return Ok(val == "1");
        }

        let status = Command::new(self.binary_name())
            .args(["-n", "true"])
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .map_err(|e| format!("Failed to check passwordless {}: {e}", self.binary_name()))?;

        Ok(status.success())
    }
}

impl fmt::Display for PrivilegeTool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.binary_name())
    }
}

// ---------------------------------------------------------------------------
// PrivilegeMode implementation
// ---------------------------------------------------------------------------

impl PrivilegeMode {
    /// What: Parse a config file value into a `PrivilegeMode`.
    ///
    /// Inputs:
    /// - `val`: Raw config string (e.g. `"auto"`, `"sudo"`, `"doas"`).
    ///
    /// Output: `Some(mode)` on recognized value, `None` otherwise.
    ///
    /// Details: Case-insensitive matching after trim.
    #[must_use]
    pub fn from_config_key(val: &str) -> Option<Self> {
        match val.trim().to_ascii_lowercase().as_str() {
            "auto" => Some(Self::Auto),
            "sudo" => Some(Self::Sudo),
            "doas" => Some(Self::Doas),
            _ => None,
        }
    }

    /// What: Return the canonical config key string for this mode.
    ///
    /// Inputs: None.
    ///
    /// Output: `"auto"`, `"sudo"`, or `"doas"`.
    ///
    /// Details: Inverse of [`from_config_key`](Self::from_config_key).
    #[must_use]
    pub const fn as_config_key(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Sudo => "sudo",
            Self::Doas => "doas",
        }
    }
}

impl fmt::Display for PrivilegeMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_config_key())
    }
}

// ---------------------------------------------------------------------------
// AuthMode
// ---------------------------------------------------------------------------

/// What: Authentication strategy for privilege escalation.
///
/// Inputs: None (enum variant selection).
///
/// Output: Controls how Pacsea handles authentication before privileged operations.
///
/// Details:
/// - `Prompt` (default): Pacsea shows its own password modal/prompt and uses stdin password
///   piping (`sudo -S`) for stdin-capable tools.
///   For tools without stdin support (doas), resolver logic coerces this mode to `Interactive`.
/// - `PasswordlessOnly`: Skip password prompt only when `{tool} -n true` succeeds;
///   fall back to `Prompt` otherwise.
/// - `Interactive`: Skip Pacsea's password capture entirely and let the privilege
///   tool handle authentication directly (fingerprint via PAM, terminal password, etc.).
///   Works with both sudo and doas when PAM is configured.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AuthMode {
    /// Pacsea captures the password for stdin-capable tools; non-stdin tools are coerced to interactive.
    #[default]
    Prompt,
    /// Skip password prompt only when passwordless escalation is available.
    PasswordlessOnly,
    /// Let the privilege tool handle authentication interactively (PAM fingerprint, etc.).
    Interactive,
}

impl AuthMode {
    /// What: Parse a config file value into an `AuthMode`.
    ///
    /// Inputs:
    /// - `val`: Raw config string (e.g. `"prompt"`, `"passwordless_only"`, `"interactive"`).
    ///
    /// Output: `Some(mode)` on recognized value, `None` otherwise.
    ///
    /// Details: Case-insensitive matching after trim; accepts underscores and hyphens.
    #[must_use]
    pub fn from_config_key(val: &str) -> Option<Self> {
        match val.trim().to_ascii_lowercase().replace('-', "_").as_str() {
            "prompt" => Some(Self::Prompt),
            "passwordless_only" | "passwordless" => Some(Self::PasswordlessOnly),
            "interactive" => Some(Self::Interactive),
            _ => None,
        }
    }

    /// What: Return the canonical config key string for this mode.
    ///
    /// Inputs: None.
    ///
    /// Output: `"prompt"`, `"passwordless_only"`, or `"interactive"`.
    ///
    /// Details: Inverse of [`from_config_key`](Self::from_config_key).
    #[must_use]
    pub const fn as_config_key(self) -> &'static str {
        match self {
            Self::Prompt => "prompt",
            Self::PasswordlessOnly => "passwordless_only",
            Self::Interactive => "interactive",
        }
    }

    /// What: Whether this mode skips Pacsea's password modal entirely.
    ///
    /// Inputs: None.
    ///
    /// Output: `true` for `Interactive`, `false` for `Prompt` and `PasswordlessOnly`.
    ///
    /// Details:
    /// - `PasswordlessOnly` does not unconditionally skip — it still needs a runtime
    ///   `{tool} -n true` check before skipping.
    /// - `Interactive` always skips the modal because the tool handles auth directly.
    #[must_use]
    pub const fn always_skips_password_modal(self) -> bool {
        matches!(self, Self::Interactive)
    }
}

impl fmt::Display for AuthMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_config_key())
    }
}

// ---------------------------------------------------------------------------
// Resolver
// ---------------------------------------------------------------------------

/// What: Resolve which privilege tool to use based on the configured mode.
///
/// Inputs:
/// - `mode`: User-configured [`PrivilegeMode`].
///
/// Output: `Ok(tool)` on success, `Err` with actionable message on failure.
///
/// # Errors
///
/// - `Auto`: neither doas nor sudo found on `$PATH`.
/// - `Sudo`/`Doas`: the explicitly requested tool is not on `$PATH`.
///
/// Details:
/// - `Auto` prefers doas over sudo when both are available.
/// - Explicit modes fail fast with a message suggesting config changes.
pub fn resolve_privilege_tool(mode: PrivilegeMode) -> Result<PrivilegeTool, String> {
    match mode {
        PrivilegeMode::Auto => {
            let doas_ok = PrivilegeTool::Doas.is_available();
            let sudo_ok = PrivilegeTool::Sudo.is_available();
            tracing::debug!(
                mode = %mode,
                doas_available = doas_ok,
                sudo_available = sudo_ok,
                "Resolving privilege tool"
            );
            if doas_ok {
                tracing::info!(
                    tool = "doas",
                    reason = "auto: doas preferred when available",
                    "Selected privilege tool"
                );
                Ok(PrivilegeTool::Doas)
            } else if sudo_ok {
                tracing::info!(
                    tool = "sudo",
                    reason = "auto: doas unavailable, falling back",
                    "Selected privilege tool"
                );
                Ok(PrivilegeTool::Sudo)
            } else {
                Err("Neither doas nor sudo found on $PATH. \
                     Install one to perform privileged operations: \
                     `pacman -S sudo` or `pacman -S opendoas`."
                    .to_string())
            }
        }
        PrivilegeMode::Sudo => {
            if PrivilegeTool::Sudo.is_available() {
                tracing::info!(
                    tool = "sudo",
                    reason = "explicit config",
                    "Selected privilege tool"
                );
                Ok(PrivilegeTool::Sudo)
            } else {
                Err(
                    "sudo is not available on $PATH. Install sudo (`pacman -S sudo`) \
                     or change privilege_tool to 'auto' or 'doas' in settings.conf."
                        .to_string(),
                )
            }
        }
        PrivilegeMode::Doas => {
            if PrivilegeTool::Doas.is_available() {
                tracing::info!(
                    tool = "doas",
                    reason = "explicit config",
                    "Selected privilege tool"
                );
                Ok(PrivilegeTool::Doas)
            } else {
                Err(
                    "doas is not available on $PATH. Install opendoas (`pacman -S opendoas`) \
                     or change privilege_tool to 'auto' or 'sudo' in settings.conf."
                        .to_string(),
                )
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Convenience resolver
// ---------------------------------------------------------------------------

/// What: Resolve the privilege tool for a given mode, applying Auto-only fallback policy.
///
/// Inputs:
/// - `mode`: Privilege selection mode (from settings, tests, or callers).
///
/// Output:
/// - `Ok(PrivilegeTool)` when resolution succeeds, including `Ok(Sudo)` after `Auto`
///   resolution failure (with warning logged).
/// - `Err(String)` with an actionable message when `Sudo` or `Doas` mode is set but that
///   binary is missing from `$PATH`.
///
/// Details:
/// - Explicit modes never substitute the other tool; `Auto` may fall back to sudo so
///   behaviour stays lenient when no privilege binary is installed.
fn active_tool_for_mode(mode: PrivilegeMode) -> Result<PrivilegeTool, String> {
    match resolve_privilege_tool(mode) {
        Ok(tool) => Ok(tool),
        Err(err) if mode == PrivilegeMode::Auto => {
            tracing::warn!(
                configured_mode = %mode,
                error = %err,
                fallback = "sudo",
                "Privilege tool auto-resolution failed — falling back to sudo; privileged commands may fail if sudo is missing"
            );
            Ok(PrivilegeTool::Sudo)
        }
        Err(err) => Err(err),
    }
}

/// What: Resolve the privilege tool using the cached application settings.
///
/// Inputs: None (reads `crate::theme::settings().privilege_mode`).
///
/// Output:
/// - `Ok(PrivilegeTool)` for successful resolution, or `Ok(Sudo)` after `Auto` failure
///   (see [`active_tool_for_mode`]).
/// - `Err(String)` when explicit `sudo` or `doas` mode cannot be satisfied.
///
/// Details:
/// - Callers should propagate or display `Err` so misconfiguration is visible.
/// - Same fallback rules as [`active_tool_for_mode`].
///
/// # Errors
///
/// Returns `Err` when [`PrivilegeMode::Sudo`] or [`PrivilegeMode::Doas`] is configured but
/// that tool is not available on `$PATH`. [`PrivilegeMode::Auto`] never errors here: it falls
/// back to [`PrivilegeTool::Sudo`] after logging a warning.
#[must_use = "caller should handle missing explicit privilege tools"]
pub fn active_tool() -> Result<PrivilegeTool, String> {
    let settings = crate::theme::settings();
    active_tool_for_mode(settings.privilege_mode)
}

// ---------------------------------------------------------------------------
// Interactive authentication
// ---------------------------------------------------------------------------

/// What: Run the privilege tool interactively to let the user authenticate.
///
/// Inputs:
/// - `tool`: Resolved privilege tool (sudo or doas).
///
/// Output:
/// - `Ok(true)` if authentication succeeded, `Ok(false)` if it failed.
///
/// # Errors
///
/// Returns `Err` if the tool binary cannot be executed.
///
/// Details:
/// - For sudo: runs `sudo -v` which validates credentials without executing a command.
///   On success, the credential cache is refreshed so subsequent `sudo` calls don't re-prompt.
/// - For doas: runs `doas true` (a no-op command) to trigger authentication.
///   If `persist` is configured in `doas.conf`, subsequent `doas` calls won't re-prompt.
///   Without `persist`, each `doas` invocation will re-prompt (known limitation).
/// - The caller is responsible for ensuring the terminal is in a state where the user
///   can interact with the prompt (e.g. not in TUI raw mode).
pub fn run_interactive_auth(tool: PrivilegeTool) -> Result<bool, String> {
    if is_integration_test_context() {
        tracing::debug!(tool = %tool, "Skipping interactive auth in integration test context");
        return Ok(true);
    }

    let mut cmd = Command::new(tool.binary_name());
    if tool.capabilities().supports_credential_refresh {
        cmd.arg("-v");
    } else {
        cmd.arg("true");
    }

    let status = cmd.status().map_err(|e| {
        format!(
            "Failed to run {} for interactive authentication: {e}",
            tool.binary_name()
        )
    })?;

    Ok(status.success())
}

// ---------------------------------------------------------------------------
// Fingerprint / PAM detection
// ---------------------------------------------------------------------------

/// What: Detect whether the active privilege tool's PAM configuration includes `pam_fprintd`.
///
/// Inputs:
/// - `tool`: Resolved privilege tool (sudo or doas).
///
/// Output:
/// - `true` if `/etc/pam.d/{tool}` exists and contains a reference to `pam_fprintd`.
///
/// Details:
/// - Reads `/etc/pam.d/sudo` or `/etc/pam.d/doas` and checks for `pam_fprintd.so`.
/// - Also checks `/etc/pam.d/system-auth` and `/etc/pam.d/system-local-login` as common
///   include targets where `pam_fprintd` may be configured instead of the tool-specific file.
/// - Informational only — never blocks execution.
/// - Returns `false` on any I/O error (missing file, permission denied).
pub fn detect_pam_fingerprint(tool: PrivilegeTool) -> bool {
    use std::fs;

    let tool_pam_path = format!("/etc/pam.d/{}", tool.binary_name());
    let pam_files = [
        tool_pam_path.as_str(),
        "/etc/pam.d/system-auth",
        "/etc/pam.d/system-local-login",
    ];

    for path in &pam_files {
        if let Ok(contents) = fs::read_to_string(path)
            && contents.contains("pam_fprintd")
        {
            tracing::debug!(path = %path, "Detected pam_fprintd in PAM configuration");
            return true;
        }
    }

    false
}

/// What: Check whether a fingerprint reader is enrolled via `fprintd-list`.
///
/// Inputs:
/// - None.
///
/// Output:
/// - `true` if `fprintd-list` reports at least one enrolled finger.
///
/// Details:
/// - Runs `fprintd-list $USER` and checks the output for enrolled fingerprint entries.
/// - Returns `false` if `fprintd-list` is not installed, the command fails, or no fingers
///   are enrolled.
/// - Does not require root; `fprintd-list` reads enrollment data via D-Bus.
/// - Informational only — never blocks execution.
pub fn detect_fprintd_enrolled() -> bool {
    let username = std::env::var("USER").unwrap_or_default();
    if username.is_empty() {
        return false;
    }

    let output = Command::new("fprintd-list").arg(&username).output();

    match output {
        Ok(out) if out.status.success() => {
            let stdout = String::from_utf8_lossy(&out.stdout);
            let has_finger = stdout.lines().any(|line| {
                let trimmed = line.trim().to_lowercase();
                trimmed.contains("left-") || trimmed.contains("right-")
            });
            if has_finger {
                tracing::debug!("fprintd-list reports enrolled fingerprint(s)");
            }
            has_finger
        }
        _ => false,
    }
}

/// What: Cached result of fingerprint availability detection.
///
/// Details:
/// - Combines PAM configuration check and `fprintd-list` enrollment check.
/// - Cached via `OnceLock` since fingerprint availability doesn't change during a session.
static FINGERPRINT_AVAILABLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();

/// What: Check whether fingerprint authentication appears to be available.
///
/// Inputs:
/// - None (uses the active privilege tool from settings).
///
/// Output:
/// - `true` if both PAM fingerprint integration and an enrolled finger are detected.
///
/// Details:
/// - Result is cached for the lifetime of the process (checked once, never re-checked).
/// - Requires both `pam_fprintd` in the tool's PAM stack AND at least one enrolled finger.
/// - Informational only — used to show a hint in the password modal, never gates execution.
#[must_use]
pub fn is_fingerprint_available() -> bool {
    *FINGERPRINT_AVAILABLE.get_or_init(|| {
        let Ok(tool) = active_tool() else {
            return false;
        };

        let pam_configured = detect_pam_fingerprint(tool);
        if !pam_configured {
            tracing::debug!(tool = %tool, "No pam_fprintd in PAM config for tool");
            return false;
        }

        let enrolled = detect_fprintd_enrolled();
        if !enrolled {
            tracing::debug!("pam_fprintd configured but no enrolled fingerprints found");
        }
        enrolled
    })
}

// ---------------------------------------------------------------------------
// Command builders
// ---------------------------------------------------------------------------

/// What: Build a privilege-escalated command string.
///
/// Inputs:
/// - `tool`: Resolved privilege tool.
/// - `command`: The unprivileged command to wrap.
///
/// Output: Shell string like `"sudo pacman -S foo"` or `"doas pacman -S foo"`.
///
/// Details: Simple prefix — does not handle password piping.
#[must_use]
pub fn build_privilege_command(tool: PrivilegeTool, command: &str) -> String {
    format!("{} {command}", tool.binary_name())
}

/// What: Build a command that pipes a password to the privilege tool via stdin.
///
/// Inputs:
/// - `tool`: Resolved privilege tool.
/// - `password`: Cleartext password.
/// - `command`: The unprivileged command to wrap.
///
/// Output:
/// - `Some(cmd)` for tools that support stdin password (sudo).
/// - `None` for tools that do not (doas).
///
/// Details:
/// - Uses `shell_single_quote` for safe password escaping.
/// - Only sudo supports `-S` (read password from stdin).
#[must_use]
pub fn build_password_pipe(tool: PrivilegeTool, password: &str, command: &str) -> Option<String> {
    if !tool.capabilities().supports_stdin_password {
        return None;
    }
    let escaped = crate::install::shell_single_quote(password);
    Some(format!(
        "printf '%s\\n' {escaped} | {} -S {command}",
        tool.binary_name()
    ))
}

/// What: Build a credential warm-up command that caches the password.
///
/// Inputs:
/// - `tool`: Resolved privilege tool.
/// - `password`: Cleartext password.
///
/// Output:
/// - `Some(cmd)` for tools that support credential refresh (sudo).
/// - `None` for tools that do not (doas).
///
/// Details:
/// - For sudo: `printf '%s\n' '<pass>' | sudo -S -v 2>/dev/null`
/// - Warms up the credential cache so subsequent sudo calls don't re-prompt.
#[must_use]
pub fn build_credential_warmup(tool: PrivilegeTool, password: &str) -> Option<String> {
    if !tool.capabilities().supports_credential_refresh {
        return None;
    }
    let escaped = crate::install::shell_single_quote(password);
    Some(format!(
        "printf '%s\\n' {escaped} | {} -S -v 2>/dev/null",
        tool.binary_name()
    ))
}

/// What: Build a credential invalidation command.
///
/// Inputs:
/// - `tool`: Resolved privilege tool.
///
/// Output:
/// - `Some(cmd)` for tools that support credential invalidation (sudo).
/// - `None` for tools that do not (doas).
///
/// Details:
/// - For sudo: `sudo -k` invalidates cached credentials.
/// - doas has no credential cache to invalidate.
#[must_use]
pub fn build_credential_invalidation(tool: PrivilegeTool) -> Option<String> {
    if !tool.capabilities().supports_credential_invalidation {
        return None;
    }
    Some(format!("{} -k", tool.binary_name()))
}

/// What: Validate a password against the privilege tool.
///
/// Inputs:
/// - `tool`: Resolved privilege tool.
/// - `password`: Password to validate.
///
/// Output:
/// - `Ok(true)` if valid, `Ok(false)` if invalid.
/// - `Err` if the tool doesn't support stdin password or the check fails.
///
/// # Errors
///
/// - Returns `Err` if the tool does not support stdin password validation.
/// - Returns `Err` if the validation command cannot be executed.
///
/// Details:
/// - Only works for tools with `supports_stdin_password` (currently sudo only).
/// - First invalidates cached credentials, then tests the password.
pub fn validate_password(tool: PrivilegeTool, password: &str) -> Result<bool, String> {
    if !tool.capabilities().supports_stdin_password {
        return Err(format!(
            "{tool} does not support password validation via stdin. \
             Configure passwordless {tool} or switch to sudo in settings.conf."
        ));
    }

    let escaped = crate::install::shell_single_quote(password);
    let bin = tool.binary_name();
    let cmd = format!("{bin} -k ; printf '%s\\n' {escaped} | {bin} -S -v 2>&1");

    let output = Command::new("sh")
        .arg("-c")
        .arg(&cmd)
        .output()
        .map_err(|e| format!("Failed to execute {bin} validation: {e}"))?;

    Ok(output.status.success())
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// What: Returns true only when running in integration test context.
///
/// Inputs: None (reads env var `PACSEA_INTEGRATION_TEST`).
///
/// Output: `true` if `PACSEA_INTEGRATION_TEST=1` is set, `false` otherwise.
///
/// Details: Guards test-only env overrides so production never honors them.
fn is_integration_test_context() -> bool {
    if !std::env::var("PACSEA_INTEGRATION_TEST").is_ok_and(|v| v == "1") {
        return false;
    }

    // Keep test-only overrides available in integration tests even when they run in
    // release mode (`cargo test --release`), while preventing normal release app runs
    // from honoring these bypass env vars.
    #[cfg(debug_assertions)]
    {
        true
    }

    #[cfg(not(debug_assertions))]
    {
        is_running_cargo_test_binary()
    }
}

/// What: Determine whether the current executable is a Cargo-generated test binary.
///
/// Inputs:
/// - None.
///
/// Output:
/// - `true` when running from `target/*/deps/*` test artifacts, otherwise `false`.
///
/// Details:
/// - Integration tests compile the library without `cfg(test)`, so this runtime check keeps
///   `PACSEA_INTEGRATION_TEST` overrides functional for `cargo test --release`.
/// - Normal `cargo run --release` / installed binaries do not execute from `target/*/deps`.
#[cfg(not(debug_assertions))]
fn is_running_cargo_test_binary() -> bool {
    let Ok(exe) = std::env::current_exe() else {
        return false;
    };
    exe.components()
        .any(|component| component.as_os_str() == "deps")
}

/// What: Public wrapper for [`is_integration_test_context`].
///
/// Inputs: None.
///
/// Output: `true` when the process is running inside the integration test harness.
///
/// Details: Exposed so `password.rs` can gate test overrides.
#[must_use]
pub fn is_integration_test() -> bool {
    is_integration_test_context()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -- PrivilegeTool -------------------------------------------------------

    #[test]
    fn tool_binary_name_sudo() {
        assert_eq!(PrivilegeTool::Sudo.binary_name(), "sudo");
    }

    #[test]
    fn tool_binary_name_doas() {
        assert_eq!(PrivilegeTool::Doas.binary_name(), "doas");
    }

    #[test]
    fn tool_display_matches_binary_name() {
        assert_eq!(format!("{}", PrivilegeTool::Sudo), "sudo");
        assert_eq!(format!("{}", PrivilegeTool::Doas), "doas");
    }

    #[test]
    fn sudo_capabilities_all_enabled() {
        let caps = PrivilegeTool::Sudo.capabilities();
        assert!(caps.supports_stdin_password);
        assert!(caps.supports_credential_refresh);
        assert!(caps.supports_credential_invalidation);
        assert!(caps.supports_askpass);
    }

    #[test]
    fn doas_capabilities_all_disabled() {
        let caps = PrivilegeTool::Doas.capabilities();
        assert!(!caps.supports_stdin_password);
        assert!(!caps.supports_credential_refresh);
        assert!(!caps.supports_credential_invalidation);
        assert!(!caps.supports_askpass);
    }

    // -- PrivilegeMode -------------------------------------------------------

    #[test]
    fn mode_from_config_key_valid() {
        assert_eq!(
            PrivilegeMode::from_config_key("auto"),
            Some(PrivilegeMode::Auto)
        );
        assert_eq!(
            PrivilegeMode::from_config_key("sudo"),
            Some(PrivilegeMode::Sudo)
        );
        assert_eq!(
            PrivilegeMode::from_config_key("doas"),
            Some(PrivilegeMode::Doas)
        );
    }

    #[test]
    fn mode_from_config_key_case_insensitive() {
        assert_eq!(
            PrivilegeMode::from_config_key("AUTO"),
            Some(PrivilegeMode::Auto)
        );
        assert_eq!(
            PrivilegeMode::from_config_key("Sudo"),
            Some(PrivilegeMode::Sudo)
        );
        assert_eq!(
            PrivilegeMode::from_config_key("DOAS"),
            Some(PrivilegeMode::Doas)
        );
    }

    #[test]
    fn mode_from_config_key_with_whitespace() {
        assert_eq!(
            PrivilegeMode::from_config_key("  auto  "),
            Some(PrivilegeMode::Auto)
        );
    }

    #[test]
    fn mode_from_config_key_invalid() {
        assert_eq!(PrivilegeMode::from_config_key(""), None);
        assert_eq!(PrivilegeMode::from_config_key("su"), None);
        assert_eq!(PrivilegeMode::from_config_key("runas"), None);
    }

    #[test]
    fn mode_as_config_key_roundtrip() {
        for mode in [
            PrivilegeMode::Auto,
            PrivilegeMode::Sudo,
            PrivilegeMode::Doas,
        ] {
            let key = mode.as_config_key();
            assert_eq!(PrivilegeMode::from_config_key(key), Some(mode));
        }
    }

    #[test]
    fn mode_default_is_auto() {
        assert_eq!(PrivilegeMode::default(), PrivilegeMode::Auto);
    }

    #[test]
    fn mode_display() {
        assert_eq!(format!("{}", PrivilegeMode::Auto), "auto");
        assert_eq!(format!("{}", PrivilegeMode::Sudo), "sudo");
        assert_eq!(format!("{}", PrivilegeMode::Doas), "doas");
    }

    // -- AuthMode -------------------------------------------------------

    #[test]
    fn auth_mode_from_config_key_valid() {
        assert_eq!(AuthMode::from_config_key("prompt"), Some(AuthMode::Prompt));
        assert_eq!(
            AuthMode::from_config_key("passwordless_only"),
            Some(AuthMode::PasswordlessOnly)
        );
        assert_eq!(
            AuthMode::from_config_key("interactive"),
            Some(AuthMode::Interactive)
        );
    }

    #[test]
    fn auth_mode_from_config_key_case_insensitive() {
        assert_eq!(AuthMode::from_config_key("PROMPT"), Some(AuthMode::Prompt));
        assert_eq!(
            AuthMode::from_config_key("Interactive"),
            Some(AuthMode::Interactive)
        );
        assert_eq!(
            AuthMode::from_config_key("PASSWORDLESS_ONLY"),
            Some(AuthMode::PasswordlessOnly)
        );
    }

    #[test]
    fn auth_mode_from_config_key_hyphen_alias() {
        assert_eq!(
            AuthMode::from_config_key("passwordless-only"),
            Some(AuthMode::PasswordlessOnly)
        );
    }

    #[test]
    fn auth_mode_from_config_key_short_alias() {
        assert_eq!(
            AuthMode::from_config_key("passwordless"),
            Some(AuthMode::PasswordlessOnly)
        );
    }

    #[test]
    fn auth_mode_from_config_key_with_whitespace() {
        assert_eq!(
            AuthMode::from_config_key("  interactive  "),
            Some(AuthMode::Interactive)
        );
    }

    #[test]
    fn auth_mode_from_config_key_invalid() {
        assert_eq!(AuthMode::from_config_key(""), None);
        assert_eq!(AuthMode::from_config_key("fingerprint"), None);
        assert_eq!(AuthMode::from_config_key("password"), None);
    }

    #[test]
    fn auth_mode_as_config_key_roundtrip() {
        for mode in [
            AuthMode::Prompt,
            AuthMode::PasswordlessOnly,
            AuthMode::Interactive,
        ] {
            let key = mode.as_config_key();
            assert_eq!(AuthMode::from_config_key(key), Some(mode));
        }
    }

    #[test]
    fn auth_mode_default_is_prompt() {
        assert_eq!(AuthMode::default(), AuthMode::Prompt);
    }

    #[test]
    fn auth_mode_display() {
        assert_eq!(format!("{}", AuthMode::Prompt), "prompt");
        assert_eq!(
            format!("{}", AuthMode::PasswordlessOnly),
            "passwordless_only"
        );
        assert_eq!(format!("{}", AuthMode::Interactive), "interactive");
    }

    #[test]
    fn auth_mode_always_skips_password_modal() {
        assert!(!AuthMode::Prompt.always_skips_password_modal());
        assert!(!AuthMode::PasswordlessOnly.always_skips_password_modal());
        assert!(AuthMode::Interactive.always_skips_password_modal());
    }

    // -- Resolver (env-controlled) -------------------------------------------

    #[test]
    fn resolve_auto_prefers_doas_when_both_available() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "sudo,doas");
        }
        let result = resolve_privilege_tool(PrivilegeMode::Auto);
        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
        assert_eq!(result, Ok(PrivilegeTool::Doas));
    }

    #[test]
    fn resolve_auto_falls_back_to_sudo() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "sudo");
        }
        let result = resolve_privilege_tool(PrivilegeMode::Auto);
        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
        assert_eq!(result, Ok(PrivilegeTool::Sudo));
    }

    #[test]
    fn resolve_auto_fails_when_none_available() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "none");
        }
        let result = resolve_privilege_tool(PrivilegeMode::Auto);
        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
        let err = result.expect_err("should fail when no tool available");
        assert!(err.contains("Neither doas nor sudo found"));
    }

    #[test]
    fn resolve_explicit_sudo_succeeds() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "sudo");
        }
        let result = resolve_privilege_tool(PrivilegeMode::Sudo);
        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
        assert_eq!(result, Ok(PrivilegeTool::Sudo));
    }

    #[test]
    fn resolve_explicit_sudo_fails_when_missing() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "doas");
        }
        let result = resolve_privilege_tool(PrivilegeMode::Sudo);
        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
        assert!(result.is_err());
        let err = result.expect_err("should fail when sudo unavailable");
        assert!(err.contains("sudo is not available"));
    }

    #[test]
    fn resolve_explicit_doas_succeeds() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "doas");
        }
        let result = resolve_privilege_tool(PrivilegeMode::Doas);
        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
        assert_eq!(result, Ok(PrivilegeTool::Doas));
    }

    #[test]
    fn resolve_explicit_doas_fails_when_missing() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "sudo");
        }
        let result = resolve_privilege_tool(PrivilegeMode::Doas);
        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
        assert!(result.is_err());
        let err = result.expect_err("should fail when doas unavailable");
        assert!(err.contains("doas is not available"));
    }

    // -- Command builders ----------------------------------------------------

    #[test]
    fn build_privilege_command_sudo() {
        let cmd = build_privilege_command(PrivilegeTool::Sudo, "pacman -S foo");
        assert_eq!(cmd, "sudo pacman -S foo");
    }

    #[test]
    fn build_privilege_command_doas() {
        let cmd = build_privilege_command(PrivilegeTool::Doas, "pacman -S foo");
        assert_eq!(cmd, "doas pacman -S foo");
    }

    #[test]
    fn build_password_pipe_sudo_returns_some() {
        let result = build_password_pipe(PrivilegeTool::Sudo, "secret", "pacman -S foo");
        let cmd = result.expect("sudo should support password pipe");
        assert!(cmd.contains("printf "));
        assert!(cmd.contains("sudo -S pacman -S foo"));
    }

    #[test]
    fn build_password_pipe_doas_returns_none() {
        let result = build_password_pipe(PrivilegeTool::Doas, "secret", "pacman -S foo");
        assert!(result.is_none());
    }

    #[test]
    fn build_credential_warmup_sudo_returns_some() {
        let result = build_credential_warmup(PrivilegeTool::Sudo, "secret");
        let cmd = result.expect("sudo should support credential warmup");
        assert!(cmd.contains("sudo -S -v"));
    }

    #[test]
    fn build_credential_warmup_doas_returns_none() {
        let result = build_credential_warmup(PrivilegeTool::Doas, "secret");
        assert!(result.is_none());
    }

    #[test]
    fn build_credential_invalidation_sudo_returns_some() {
        let cmd = build_credential_invalidation(PrivilegeTool::Sudo)
            .expect("sudo should support credential invalidation");
        assert_eq!(cmd, "sudo -k");
    }

    #[test]
    fn build_credential_invalidation_doas_returns_none() {
        let result = build_credential_invalidation(PrivilegeTool::Doas);
        assert!(result.is_none());
    }

    // -- Password validation -------------------------------------------------

    #[test]
    fn validate_password_doas_returns_err() {
        let result = validate_password(PrivilegeTool::Doas, "any");
        let err = result.expect_err("doas should not support password validation");
        assert!(err.contains("does not support"));
    }

    // -- Availability (env-controlled) ---------------------------------------

    #[test]
    fn is_available_test_override_none() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "none");
        }
        assert!(!PrivilegeTool::Sudo.is_available());
        assert!(!PrivilegeTool::Doas.is_available());
        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
    }

    #[test]
    fn is_available_test_override_sudo_only() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "sudo");
        }
        assert!(PrivilegeTool::Sudo.is_available());
        assert!(!PrivilegeTool::Doas.is_available());
        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
    }

    #[test]
    fn is_available_test_override_both() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "sudo,doas");
        }
        assert!(PrivilegeTool::Sudo.is_available());
        assert!(PrivilegeTool::Doas.is_available());
        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
    }

    // -- is_integration_test -------------------------------------------------

    #[test]
    fn is_integration_test_when_set() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
        }
        assert!(is_integration_test());
        unsafe {
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
    }

    #[test]
    fn is_integration_test_when_unset() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
        assert!(!is_integration_test());
    }

    #[test]
    fn is_integration_test_wrong_value() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "0");
        }
        assert!(!is_integration_test());
        unsafe {
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
    }

    // -- active_tool ---------------------------------------------------------

    #[test]
    fn active_tool_returns_ok_with_sudo_or_doas() {
        let tool = active_tool().expect("active_tool should resolve in this environment");
        assert!(
            tool == PrivilegeTool::Sudo || tool == PrivilegeTool::Doas,
            "active_tool should return Sudo or Doas"
        );
    }

    #[test]
    fn active_tool_for_mode_explicit_doas_errors_when_missing() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "sudo");
        }
        let result = super::active_tool_for_mode(PrivilegeMode::Doas);
        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
        let err = result.expect_err("explicit doas without doas on PATH should error");
        assert!(err.contains("doas is not available"));
    }

    #[test]
    fn active_tool_for_mode_explicit_sudo_errors_when_missing() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "doas");
        }
        let result = super::active_tool_for_mode(PrivilegeMode::Sudo);
        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
        let err = result.expect_err("explicit sudo without sudo on PATH should error");
        assert!(err.contains("sudo is not available"));
    }

    #[test]
    fn active_tool_for_mode_auto_none_falls_back_to_sudo() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "none");
        }
        let result = super::active_tool_for_mode(PrivilegeMode::Auto);
        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
        assert_eq!(
            result,
            Ok(PrivilegeTool::Sudo),
            "Auto with no tools should still return Ok(Sudo) after fallback"
        );
    }

    // -- Password pipe format ------------------------------------------------

    #[test]
    fn build_password_pipe_uses_printf_not_echo() {
        let result = build_password_pipe(PrivilegeTool::Sudo, "pw", "cmd");
        let cmd = result.expect("sudo pipe should return Some");
        assert!(cmd.starts_with("printf "), "should use printf, not echo");
        assert!(cmd.contains("%s\\n"), "should use %s\\n format");
    }

    #[test]
    fn build_password_pipe_escapes_special_chars() {
        let result = build_password_pipe(PrivilegeTool::Sudo, "pa's$word", "pacman -S foo");
        let cmd = result.expect("sudo pipe should return Some");
        assert!(cmd.contains("sudo -S pacman -S foo"));
        assert!(!cmd.contains("pa's$word"), "password must be shell-escaped");
    }

    #[test]
    fn build_credential_warmup_uses_printf() {
        let result = build_credential_warmup(PrivilegeTool::Sudo, "pw");
        let cmd = result.expect("sudo warmup should return Some");
        assert!(cmd.starts_with("printf "), "warmup should use printf");
        assert!(cmd.contains("sudo -S -v"));
        assert!(cmd.contains("2>/dev/null"));
    }

    // -- Doas command builders -----------------------------------------------

    #[test]
    fn build_privilege_command_doas_format() {
        let cmd = build_privilege_command(PrivilegeTool::Doas, "pacman -Syu --noconfirm");
        assert_eq!(cmd, "doas pacman -Syu --noconfirm");
    }

    #[test]
    fn doas_password_pipe_returns_none() {
        assert!(build_password_pipe(PrivilegeTool::Doas, "pw", "cmd").is_none());
    }

    #[test]
    fn doas_credential_warmup_returns_none() {
        assert!(build_credential_warmup(PrivilegeTool::Doas, "pw").is_none());
    }

    #[test]
    fn doas_credential_invalidation_returns_none() {
        assert!(build_credential_invalidation(PrivilegeTool::Doas).is_none());
    }

    // -- Passwordless check --------------------------------------------------

    #[test]
    fn check_passwordless_test_override_true() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_SUDO_PASSWORDLESS", "1");
        }
        let result = PrivilegeTool::Sudo.check_passwordless();
        unsafe {
            std::env::remove_var("PACSEA_TEST_SUDO_PASSWORDLESS");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
        assert_eq!(result, Ok(true));
    }

    #[test]
    fn check_passwordless_test_override_false() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_SUDO_PASSWORDLESS", "0");
        }
        let result = PrivilegeTool::Sudo.check_passwordless();
        unsafe {
            std::env::remove_var("PACSEA_TEST_SUDO_PASSWORDLESS");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
        assert_eq!(result, Ok(false));
    }

    #[test]
    fn check_passwordless_doas_test_override() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_SUDO_PASSWORDLESS", "1");
        }
        let result = PrivilegeTool::Doas.check_passwordless();
        unsafe {
            std::env::remove_var("PACSEA_TEST_SUDO_PASSWORDLESS");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }
        assert_eq!(result, Ok(true));
    }

    // -- Validate password ---------------------------------------------------

    #[test]
    fn validate_password_doas_returns_unsupported() {
        let result = validate_password(PrivilegeTool::Doas, "any");
        let err = result.expect_err("doas should not support password validation");
        assert!(
            err.contains("does not support"),
            "unexpected error message: {err}"
        );
    }

    // -- Tool symmetry -------------------------------------------------------

    #[test]
    fn both_tools_produce_distinct_commands() {
        let sudo_cmd = build_privilege_command(PrivilegeTool::Sudo, "pacman -S foo");
        let doas_cmd = build_privilege_command(PrivilegeTool::Doas, "pacman -S foo");
        assert_ne!(sudo_cmd, doas_cmd, "sudo and doas commands must differ");
        assert!(sudo_cmd.starts_with("sudo "));
        assert!(doas_cmd.starts_with("doas "));
    }

    #[test]
    fn capabilities_are_complementary() {
        let sudo_caps = PrivilegeTool::Sudo.capabilities();
        let doas_caps = PrivilegeTool::Doas.capabilities();
        assert_ne!(
            sudo_caps.supports_stdin_password, doas_caps.supports_stdin_password,
            "sudo and doas should differ on stdin password support"
        );
    }

    // -- Fingerprint detection ------------------------------------------------

    #[test]
    fn detect_pam_fingerprint_sudo_does_not_panic() {
        // Returns true only if /etc/pam.d/sudo (or system-auth) has pam_fprintd.
        // In CI or most test machines this is false; we verify no panic.
        let _result = detect_pam_fingerprint(PrivilegeTool::Sudo);
    }

    #[test]
    fn detect_pam_fingerprint_doas_does_not_panic() {
        let _result = detect_pam_fingerprint(PrivilegeTool::Doas);
    }

    #[test]
    fn detect_fprintd_enrolled_does_not_panic() {
        let _result = detect_fprintd_enrolled();
    }

    #[test]
    fn is_fingerprint_available_does_not_panic() {
        let _result = is_fingerprint_available();
    }
}