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
//! Command-line update functionality.

#[cfg(not(target_os = "windows"))]
use crate::args::i18n;
#[cfg(not(target_os = "windows"))]
use crate::args::utils;
#[cfg(not(target_os = "windows"))]
use pacsea::install::shell_single_quote;
#[cfg(not(target_os = "windows"))]
use pacsea::state::SecureString;
#[cfg(not(target_os = "windows"))]
use pacsea::theme;
#[cfg(not(target_os = "windows"))]
use std::path::Path;
#[cfg(not(target_os = "windows"))]
use tracing::{debug, warn};

/// What: Format text with ANSI color codes if colors are enabled.
///
/// Inputs:
/// - `text`: The text to format.
/// - `color_code`: ANSI color code (e.g., "32" for green, "31" for red).
/// - `no_color`: If true, returns text without color codes.
///
/// Output:
/// - Colored text string if colors enabled, plain text otherwise.
///
/// Details:
/// - Uses ANSI escape sequences for terminal colors.
/// - Respects the `no_color` flag to disable coloring.
#[cfg(not(target_os = "windows"))]
fn colorize(text: &str, color_code: &str, no_color: bool) -> String {
    if no_color {
        text.to_string()
    } else {
        format!("\x1b[{color_code}m{text}\x1b[0m")
    }
}

/// What: Format success messages in green.
///
/// Inputs:
/// - `text`: The text to format.
/// - `no_color`: If true, returns text without color codes.
///
/// Output:
/// - Green colored text string if colors enabled, plain text otherwise.
#[cfg(not(target_os = "windows"))]
fn success_color(text: &str, no_color: bool) -> String {
    colorize(text, "32", no_color) // Green
}

/// What: Format error messages in red.
///
/// Inputs:
/// - `text`: The text to format.
/// - `no_color`: If true, returns text without color codes.
///
/// Output:
/// - Red colored text string if colors enabled, plain text otherwise.
#[cfg(not(target_os = "windows"))]
fn error_color(text: &str, no_color: bool) -> String {
    colorize(text, "31", no_color) // Red
}

/// What: Format info messages in cyan.
///
/// Inputs:
/// - `text`: The text to format.
/// - `no_color`: If true, returns text without color codes.
///
/// Output:
/// - Cyan colored text string if colors enabled, plain text otherwise.
#[cfg(not(target_os = "windows"))]
fn info_color(text: &str, no_color: bool) -> String {
    colorize(text, "36", no_color) // Cyan
}

/// What: Format warning messages in yellow.
///
/// Inputs:
/// - `text`: The text to format.
/// - `no_color`: If true, returns text without color codes.
///
/// Output:
/// - Yellow colored text string if colors enabled, plain text otherwise.
#[cfg(not(target_os = "windows"))]
fn warning_color(text: &str, no_color: bool) -> String {
    colorize(text, "33", no_color) // Yellow
}

/// What: Format a file path as a clickable hyperlink in the terminal using OSC 8 escape sequences.
///
/// Inputs:
/// - `path`: The file path to make clickable.
///
/// Output:
/// - A string containing the path formatted as a clickable hyperlink.
///
/// Details:
/// - Uses OSC 8 escape sequences to create clickable links in modern terminals.
/// - Converts the path to an absolute file:// URL.
/// - Handles paths that may not exist yet by using absolute path resolution.
#[cfg(not(target_os = "windows"))]
fn format_clickable_path(path: &Path) -> String {
    // Try to get absolute path - canonicalize if file exists, otherwise resolve relative to current dir
    let absolute_path = if path.exists() {
        path.canonicalize().unwrap_or_else(|_| {
            std::env::current_dir()
                .ok()
                .and_then(|cwd| cwd.join(path).canonicalize().ok())
                .unwrap_or_else(|| path.to_path_buf())
        })
    } else {
        // File doesn't exist yet, try to resolve relative to current directory
        if path.is_absolute() {
            path.to_path_buf()
        } else {
            std::env::current_dir()
                .ok()
                .map_or_else(|| path.to_path_buf(), |cwd| cwd.join(path))
        }
    };
    let path_str = absolute_path.to_string_lossy();
    let file_url = format!("file://{path_str}");
    format!("\x1b]8;;{file_url}\x1b\\{path_str}\x1b]8;;\x1b\\")
}

/// What: Extract failed package names from pacman error output.
///
/// Inputs:
/// - `output`: The pacman command output text to parse.
///
/// Output:
/// - Vector of failed package names.
///
/// Details:
/// - Parses various pacman error patterns including "target not found", transaction failures, etc.
/// - Handles both English and German error messages.
#[cfg(not(target_os = "windows"))]
#[allow(clippy::similar_names)]
fn extract_failed_packages_from_pacman(output: &str) -> Vec<String> {
    let mut failed = Vec::new();
    let lines: Vec<&str> = output.lines().collect();
    let mut in_error_section = false;
    let mut in_conflict_section = false;

    // Get locale-specific error patterns from i18n
    let target_not_found = i18n::t("app.cli.update.pacman_errors.target_not_found").to_lowercase();
    let failed_to_commit = i18n::t("app.cli.update.pacman_errors.failed_to_commit").to_lowercase();
    let failed_to_prepare =
        i18n::t("app.cli.update.pacman_errors.failed_to_prepare").to_lowercase();
    let error_prefix = i18n::t("app.cli.update.pacman_errors.error_prefix").to_lowercase();
    let resolving = i18n::t("app.cli.update.pacman_errors.resolving").to_lowercase();
    let looking_for = i18n::t("app.cli.update.pacman_errors.looking_for").to_lowercase();
    let package_word = i18n::t("app.cli.update.pacman_errors.package").to_lowercase();
    let packages_word = i18n::t("app.cli.update.pacman_errors.packages").to_lowercase();
    let error_word = i18n::t("app.cli.update.pacman_errors.error").to_lowercase();
    let failed_word = i18n::t("app.cli.update.pacman_errors.failed").to_lowercase();
    let transaction_word = i18n::t("app.cli.update.pacman_errors.transaction").to_lowercase();
    let conflicting_word = i18n::t("app.cli.update.pacman_errors.conflicting").to_lowercase();
    let files_word = i18n::t("app.cli.update.pacman_errors.files").to_lowercase();

    for line in &lines {
        let trimmed = line.trim();
        let lower = trimmed.to_lowercase();

        // Pattern 1: "error: target not found: package-name"
        if lower.contains(&target_not_found) {
            // Extract package name after "not found:" or similar
            if let Some(colon_pos) = trimmed.rfind(':') {
                let after_colon = &trimmed[colon_pos + 1..].trim();
                // Package name should be alphanumeric with dashes/underscores
                if after_colon
                    .chars()
                    .all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '/')
                {
                    // Remove any trailing punctuation
                    let pkg = after_colon.trim_end_matches(|c: char| {
                        !c.is_alphanumeric() && c != '-' && c != '_' && c != '/'
                    });
                    if !pkg.is_empty() && pkg.len() > 1 {
                        failed.push(pkg.to_string());
                    }
                }
            }
            in_error_section = true;
        }
        // Pattern 2: "error: failed to commit transaction" or similar
        else if lower.contains(&failed_to_commit) || lower.contains(&failed_to_prepare) {
            in_error_section = true;
            in_conflict_section = true;
        }
        // Pattern 3: Look for package names in error context
        else if in_error_section || in_conflict_section {
            // Look for lines that might contain package names
            // Skip common error message text
            if !trimmed.is_empty()
                && !lower.starts_with(&format!("{error_prefix}:"))
                && !lower.contains(&resolving)
                && !lower.contains(&looking_for)
                && !lower.contains("::")
            {
                // Check if line looks like it contains package names
                // Package names are typically: alphanumeric, dashes, underscores, slashes
                let words: Vec<&str> = trimmed.split_whitespace().collect();
                for word in words {
                    let clean_word = word.trim_matches(|c: char| {
                        !c.is_alphanumeric() && c != '-' && c != '_' && c != '/' && c != ':'
                    });
                    // Valid package name: 2+ chars, alphanumeric with dashes/underscores/slashes
                    if clean_word.len() >= 2
                        && clean_word.chars().all(|c| {
                            c.is_alphanumeric() || c == '-' || c == '_' || c == '/' || c == ':'
                        })
                        && clean_word.contains(|c: char| c.is_alphanumeric())
                    {
                        // Avoid common false positives using locale-specific words
                        if !clean_word.eq_ignore_ascii_case(&package_word)
                            && !clean_word.eq_ignore_ascii_case(&packages_word)
                            && !clean_word.eq_ignore_ascii_case(&error_word)
                            && !clean_word.eq_ignore_ascii_case(&failed_word)
                            && !clean_word.eq_ignore_ascii_case(&transaction_word)
                            && !clean_word.eq_ignore_ascii_case(&conflicting_word)
                            && !clean_word.eq_ignore_ascii_case(&files_word)
                        {
                            failed.push(clean_word.to_string());
                        }
                    }
                }
            }
            // Reset error section on empty lines or new error messages
            if trimmed.is_empty() || lower.starts_with(&format!("{error_prefix}:")) {
                in_error_section = false;
                in_conflict_section = false;
            }
        }
        // Pattern 4: Look for package names after "::" separator (pacman format: repo::package)
        else if trimmed.contains("::") {
            let parts: Vec<&str> = trimmed.split("::").collect();
            if parts.len() == 2 {
                let pkg_part = parts[1].split_whitespace().next().unwrap_or("");
                if pkg_part
                    .chars()
                    .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
                    && pkg_part.len() >= 2
                {
                    failed.push(pkg_part.to_string());
                }
            }
        }
    }
    failed
}

/// What: Extract failed package names from command output.
///
/// Inputs:
/// - `output`: The command output text to parse.
/// - `helper`: The AUR helper name (yay/paru) or "pacman" for official packages.
///
/// Output:
/// - Vector of failed package names.
///
/// Details:
/// - Parses yay/paru output for lines like "package - exit status X".
/// - Uses locale-independent pattern matching (exit status pattern is universal).
/// - Does not rely on locale-specific error messages.
#[cfg(not(target_os = "windows"))]
fn extract_failed_packages(output: &str, helper: &str) -> Vec<String> {
    let mut failed = if helper == "pacman" {
        extract_failed_packages_from_pacman(output)
    } else {
        // For yay/paru, primarily rely on the universal " - exit status" pattern
        // This pattern appears to be locale-independent
        let mut failed_aur = Vec::new();
        let lines: Vec<&str> = output.lines().collect();

        // Look for lines with "exit status" pattern - this is the most reliable indicator
        // Format: "package - exit status X" (works across locales)
        for line in &lines {
            if line.contains(" - exit status")
                && let Some(pkg) = line.split(" - exit status").next()
            {
                let pkg = pkg.trim();
                // Remove common prefixes like "->" that yay/paru use
                let pkg = pkg.strip_prefix("->").unwrap_or(pkg).trim();
                if !pkg.is_empty() {
                    failed_aur.push(pkg.to_string());
                }
            }
        }

        // If we didn't find any via exit status pattern, try to find packages
        // in a section that follows common structural markers
        if failed_aur.is_empty() {
            // Look for sections that typically contain failed packages
            // These sections usually have markers like "->" followed by package lists
            let mut in_package_list = false;
            for line in &lines {
                let trimmed = line.trim();

                // Detect start of package list section (common markers)
                // Look for lines with "->" that might indicate a list section
                if trimmed.starts_with("->") && trimmed.len() > 2 {
                    // Check if the rest looks like it might be a header/description
                    // If it contains common words, it's probably a header, not a package
                    let after_arrow = &trimmed[2..].trim();
                    if after_arrow.chars().all(|c| !c.is_whitespace() && c != ':') {
                        // Might be a package name
                        if after_arrow
                            .chars()
                            .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
                        {
                            failed_aur.push((*after_arrow).to_string());
                            in_package_list = true;
                        }
                    } else {
                        in_package_list = true;
                    }
                } else if in_package_list {
                    // In package list, look for package-like strings
                    if !trimmed.is_empty()
                        && !trimmed.starts_with("==>")
                        && !trimmed.contains("exit status")
                        && trimmed
                            .chars()
                            .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
                    {
                        failed_aur.push(trimmed.to_string());
                    } else if trimmed.is_empty() || trimmed.starts_with("==>") {
                        // Empty line or new section marker ends the list
                        in_package_list = false;
                    }
                }
            }
        }
        failed_aur
    };

    // Deduplicate and return
    failed.sort();
    failed.dedup();

    // Additional cleanup: remove very short strings and common false positives
    failed.retain(|pkg| {
        pkg.len() >= 2
            && !pkg.eq_ignore_ascii_case("package")
            && !pkg.eq_ignore_ascii_case("packages")
            && !pkg.eq_ignore_ascii_case("error")
            && !pkg.eq_ignore_ascii_case("failed")
    });

    failed
}

/// What: Execute a command with output both displayed in real-time and logged to file using tee.
///
/// Inputs:
/// - `program`: The program to execute.
/// - `args`: Command arguments.
/// - `log_file_path`: Path to the log file where output should be written.
/// - `password`: Optional sudo password; when provided, uses `sudo -S` with password piping.
/// - `interactive_auth`: When true, inherits stdin so the privilege tool can handle
///   authentication directly (PAM fingerprint, terminal password prompt, etc.).
///   When false, stdin is `/dev/null` to prevent unintended interactive prompts.
///
/// Output:
/// - `Ok((status, output))` if command executed, `Err(e)` if execution failed.
///
/// Details:
/// - Uses a shell wrapper with `tee` to duplicate output to both terminal and log file.
/// - Preserves real-time output display while logging everything.
/// - Returns the command output for parsing failed packages.
/// - Output is parsed using locale-aware i18n patterns.
/// - Sets `LC_ALL=C` and `LANG=C` for consistent English output.
/// - Handles TTY detection and falls back to stdout if no TTY available.
/// - Uses `set -o pipefail` for reliable exit status capture.
/// - Configures stdin/stdout/stderr explicitly; inherits stdin for interactive auth.
#[cfg(not(target_os = "windows"))]
fn run_command_with_logging(
    program: &str,
    args: &[&str],
    log_file_path: &Path,
    password: Option<&str>,
    interactive_auth: bool,
) -> Result<(std::process::ExitStatus, String), std::io::Error> {
    use std::io::IsTerminal;
    use std::process::{Command, Stdio};

    let log_file_str = log_file_path.to_string_lossy();
    let args_str = args
        .iter()
        .map(|a| shell_single_quote(a))
        .collect::<Vec<_>>()
        .join(" ");

    // Check if stdout is a TTY for /dev/tty redirection
    let has_tty = std::io::stdout().is_terminal();
    let tty_redirect = if has_tty {
        "> /dev/tty"
    } else {
        "> /dev/stdout"
    };

    // Use bash -c with tee to both display and log output
    // Redirect both stdout and stderr through tee
    // Use set -o pipefail for reliable exit status capture
    // Also capture output to a temp file so we can read it back
    let temp_output =
        std::env::temp_dir().join(format!("pacsea_update_output_{}.txt", std::process::id()));
    let temp_output_str = temp_output.to_string_lossy();

    // Build the command with optional password piping for privilege tools.
    // When program is the active privilege tool, handle password piping.
    // When program is not a privilege tool (e.g., paru/yay), use directly.
    let tool = pacsea::logic::privilege::active_tool().map_err(std::io::Error::other)?;
    let full_command = if program == tool.binary_name() {
        password.map_or_else(
            || pacsea::logic::privilege::build_privilege_command(tool, &args_str),
            |pass| {
                args.first().map_or_else(
                    || {
                        pacsea::logic::privilege::build_password_pipe(tool, pass, &args_str)
                            .unwrap_or_else(|| {
                                pacsea::logic::privilege::build_privilege_command(tool, &args_str)
                            })
                    },
                    |cmd| {
                        let cmd_escaped = shell_single_quote(cmd);
                        let cmd_args = &args[1..];
                        let cmd_args_str = cmd_args
                            .iter()
                            .map(|a| shell_single_quote(a))
                            .collect::<Vec<_>>()
                            .join(" ");
                        let base = if cmd_args_str.is_empty() {
                            cmd_escaped
                        } else {
                            format!("{cmd_escaped} {cmd_args_str}")
                        };
                        pacsea::logic::privilege::build_password_pipe(tool, pass, &base)
                            .unwrap_or_else(|| {
                                pacsea::logic::privilege::build_privilege_command(tool, &base)
                            })
                    },
                )
            },
        )
    } else {
        let program_escaped = shell_single_quote(program);
        format!("{program_escaped} {args_str}")
    };

    // Use tee twice: first logs to file, second captures to tempfile and displays
    // set -o pipefail ensures exit status reflects command failure, not tee
    // Use stdbuf -oL -eL to force line buffering so progress output appears immediately
    // command 2>&1 | tee -a logfile | tee tempfile > /dev/tty
    // This way: output is displayed once, logged to file, and captured to tempfile
    let log_file_escaped = shell_single_quote(&log_file_str);
    let temp_output_escaped = shell_single_quote(&temp_output_str);
    let shell_cmd = format!(
        "set -o pipefail; stdbuf -oL -eL {full_command} 2>&1 | tee -a {log_file_escaped} | tee {temp_output_escaped} {tty_redirect}"
    );

    let shell_cmd_log = if program == tool.binary_name() && password.is_some() {
        let bin = tool.binary_name();
        format!(
            "set -o pipefail; stdbuf -oL -eL {bin} {args_str} 2>&1 | tee -a {log_file_escaped} | tee {temp_output_escaped} {tty_redirect}"
        )
    } else {
        shell_cmd.clone()
    };

    debug!(
        program,
        args = ?args,
        uses_password = password.is_some(),
        has_tty,
        log_file = %log_file_path.display(),
        temp_output = %temp_output.display(),
        shell_cmd = %shell_cmd_log,
        "executing update command with logging"
    );

    let stdin_cfg = if interactive_auth {
        Stdio::inherit()
    } else {
        Stdio::null()
    };

    let status = Command::new("bash")
        .arg("-c")
        .arg(&shell_cmd)
        .env("LC_ALL", "C")
        .env("LANG", "C")
        .stdin(stdin_cfg)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .status()
        .map_err(|err| {
            warn!(
                program,
                args = ?args,
                log_file = %log_file_path.display(),
                error = %err,
                "failed to spawn update command"
            );
            err
        })?;

    // Read the captured output
    let output = match std::fs::read_to_string(&temp_output) {
        Ok(content) => content,
        Err(err) => {
            warn!(
                path = %temp_output.display(),
                error = %err,
                "failed to read update temp output"
            );
            String::new()
        }
    };

    // Clean up temp file
    if let Err(err) = std::fs::remove_file(&temp_output) {
        debug!(
            path = %temp_output.display(),
            error = %err,
            "failed to remove temp output file"
        );
    }

    debug!(
        program,
        args = ?args,
        status = ?status,
        status_code = status.code(),
        output_len = output.len(),
        log_file = %log_file_path.display(),
        "update command finished"
    );

    Ok((status, output))
}

/// What: State tracking structure for system update operations.
///
/// Details:
/// - Tracks success/failure status of pacman and AUR updates.
/// - Maintains lists of failed commands and packages.
/// - Used to aggregate results across multiple update operations.
#[cfg(not(target_os = "windows"))]
struct UpdateState {
    /// Overall success status (true if all operations succeeded).
    all_succeeded: bool,
    /// List of failed command names.
    failed_commands: Vec<String>,
    /// List of failed package names.
    failed_packages: Vec<String>,
    /// Pacman update success status (None = not run, Some(true) = success, Some(false) = failed).
    pacman_succeeded: Option<bool>,
    /// AUR update success status (None = not run, Some(true) = success, Some(false) = failed).
    aur_succeeded: Option<bool>,
    /// Name of the AUR helper used (paru/yay).
    aur_helper_name: Option<String>,
}

#[cfg(not(target_os = "windows"))]
impl UpdateState {
    /// What: Create a new `UpdateState` with default values.
    ///
    /// Inputs:
    /// - None (no parameters required).
    ///
    /// Output:
    /// - A new `UpdateState` instance with all fields initialized.
    ///
    /// Details:
    /// - Initializes `all_succeeded` to `true`.
    /// - Initializes all collections (`failed_commands`, `failed_packages`) as empty vectors.
    /// - Sets all optional status fields (`pacman_succeeded`, `aur_succeeded`, `aur_helper_name`) to `None`.
    const fn new() -> Self {
        Self {
            all_succeeded: true,
            failed_commands: Vec::new(),
            failed_packages: Vec::new(),
            pacman_succeeded: None,
            aur_succeeded: None,
            aur_helper_name: None,
        }
    }
}

/// What: Prompt user for sudo password and validate it is not empty.
///
/// Inputs:
/// - `write_log`: Function to write log messages.
///
/// Output:
/// - `Some(password)` if password is valid and non-empty, `None` if passwordless sudo works.
/// - Exits the process with code 1 if password is empty or cannot be read.
///
/// Details:
/// - Uses [`pacsea::logic::password::resolve_auth_mode`] to determine auth strategy.
/// - `Interactive` mode: returns `None` (privilege tool handles auth directly via PAM).
/// - `PasswordlessOnly` mode: returns `None` if `{tool} -n true` succeeds.
/// - `Prompt` mode: prompts user for password using `rpassword::prompt_password`.
/// - Validates that password is not empty (after trimming whitespace).
/// - Empty passwords are rejected early to prevent sudo failures.
#[cfg(not(target_os = "windows"))]
fn prompt_and_validate_password(write_log: &(dyn Fn(&str) + Send + Sync)) -> Option<SecureString> {
    use std::io::IsTerminal;

    let settings = theme::settings();
    let auth_mode = pacsea::logic::password::resolve_auth_mode(&settings);

    match auth_mode {
        pacsea::logic::privilege::AuthMode::Interactive => {
            write_log(
                "Auth mode is 'interactive'; skipping password prompt (privilege tool handles auth)",
            );
            return None;
        }
        pacsea::logic::privilege::AuthMode::PasswordlessOnly => {
            if pacsea::logic::password::should_use_passwordless_sudo(&settings) {
                write_log("Passwordless privilege enabled and available, skipping password prompt");
                return None;
            }
        }
        pacsea::logic::privilege::AuthMode::Prompt => {}
    }

    // Password required, but check if stdin is available for interactive input
    if !std::io::stdin().is_terminal() {
        // Not in an interactive terminal (e.g., in tests or non-interactive environment)
        let error_msg =
            "Password required but stdin is not a terminal. Cannot prompt for password.";
        eprintln!("{}", i18n::t_fmt1("app.cli.update.error_prefix", error_msg));
        write_log("FAILED: Password required but stdin is not a terminal");
        tracing::error!("Password required but stdin is not a terminal");
        std::process::exit(1);
    }

    // Password required, prompt user
    // Get username to mimic sudo's password prompt format
    let username = std::env::var("USER").unwrap_or_else(|_| "user".to_string());
    let password_prompt = i18n::t_fmt1("app.cli.update.password_prompt", &username);
    match rpassword::prompt_password(&password_prompt) {
        Ok(pass) => {
            // Validate that password is not empty
            // Empty passwords will cause sudo to fail, so reject them early
            let trimmed_pass = pass.trim();
            if trimmed_pass.is_empty() {
                let error_msg = "Empty password provided. Password cannot be empty.";
                eprintln!("{}", i18n::t_fmt1("app.cli.update.error_prefix", error_msg));
                write_log("FAILED: Empty password provided");
                tracing::error!("Empty password provided");
                std::process::exit(1);
            }
            write_log("Password obtained from user (not logged)");
            // Return trimmed password to ensure consistency with validation
            Some(SecureString::from(trimmed_pass))
        }
        Err(e) => {
            eprintln!("{}", i18n::t_fmt1("app.cli.update.error_prefix", &e));
            write_log(&format!("FAILED: Could not read password: {e}"));
            tracing::error!("Failed to read sudo password: {e}");
            std::process::exit(1);
        }
    }
}

/// What: Create and setup the update log file, returning a `write_log` closure.
///
/// Inputs:
/// - `log_file_path`: Path to the log file.
///
/// Output:
/// - A closure that writes timestamped messages to the log file.
///
/// Details:
/// - Ensures the log file's parent directory exists.
/// - Creates a closure that appends timestamped messages to the log file.
#[cfg(not(target_os = "windows"))]
fn setup_log_file(log_file_path: &std::path::Path) -> Box<dyn Fn(&str) + Send + Sync> {
    use std::fs::OpenOptions;
    use std::io::Write;
    use std::time::{SystemTime, UNIX_EPOCH};

    // Ensure log file exists and is writable
    if let Some(parent) = log_file_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }

    // Clone the path for the closure
    let log_path = log_file_path.to_path_buf();

    // Return closure that writes to log file
    Box::new(move |message: &str| {
        if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(&log_path) {
            let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).map_or_else(
                |_| "unknown".to_string(),
                |d| pacsea::util::ts_to_date(Some(i64::try_from(d.as_secs()).unwrap_or(0))),
            );
            let _ = writeln!(file, "[{timestamp}] {message}");
        }
    })
}

/// What: Execute pacman system update and update the state accordingly.
///
/// Inputs:
/// - `state`: Mutable reference to `UpdateState` to update.
/// - `log_file_path`: Path to the log file.
/// - `password`: Optional sudo password.
/// - `no_color`: If true, disables colored output.
/// - `interactive_auth`: Whether to use interactive auth (stdin inherited for PAM).
/// - `write_log`: Function to write log messages.
///
/// Output:
/// - None (modifies state in place).
///
/// Details:
/// - Runs `sudo pacman -Syu --noconfirm` to update official packages.
/// - Updates state with success/failure status and failed packages.
/// - Extracts failed package names from command output on failure.
/// - Logs all operations and status messages to the log file.
#[cfg(not(target_os = "windows"))]
fn run_pacman_update(
    state: &mut UpdateState,
    log_file_path: &Path,
    password: Option<&str>,
    no_color: bool,
    interactive_auth: bool,
    write_log: &(dyn Fn(&str) + Send + Sync),
) {
    println!(
        "{}",
        info_color(&i18n::t("app.cli.update.starting"), no_color)
    );
    write_log("Starting system update: pacman -Syu --noconfirm");

    let tool = match pacsea::logic::privilege::active_tool() {
        Ok(t) => t,
        Err(err) => {
            println!(
                "{}",
                error_color(&i18n::t("app.cli.update.pacman_exec_failed"), no_color)
            );
            eprintln!("{}", error_color(&err, no_color));
            write_log(&format!("FAILED: Could not resolve privilege tool: {err}"));
            state.all_succeeded = false;
            state
                .failed_commands
                .push("pacman -Syu --noconfirm".to_string());
            state.pacman_succeeded = Some(false);
            return;
        }
    };
    let pacman_result = run_command_with_logging(
        tool.binary_name(),
        &["pacman", "-Syu", "--noconfirm"],
        log_file_path,
        password,
        interactive_auth,
    );

    match pacman_result {
        Ok((status, output)) => {
            if status.success() {
                println!(
                    "{}",
                    success_color(&i18n::t("app.cli.update.pacman_success"), no_color)
                );
                write_log("SUCCESS: pacman -Syu --noconfirm completed successfully");
                state.pacman_succeeded = Some(true);
            } else {
                println!(
                    "{}",
                    error_color(&i18n::t("app.cli.update.pacman_failed"), no_color)
                );
                write_log(&format!(
                    "FAILED: pacman -Syu --noconfirm failed with exit code {:?}",
                    status.code()
                ));
                let packages = extract_failed_packages(&output, "pacman");
                state.failed_packages.extend(packages);
                state.all_succeeded = false;
                state.failed_commands.push("pacman -Syu".to_string());
                state.pacman_succeeded = Some(false);
            }
        }
        Err(e) => {
            println!(
                "{}",
                error_color(&i18n::t("app.cli.update.pacman_exec_failed"), no_color)
            );
            eprintln!(
                "{}",
                error_color(&i18n::t_fmt1("app.cli.update.error_prefix", &e), no_color)
            );
            write_log(&format!(
                "FAILED: Could not execute pacman -Syu --noconfirm: {e}"
            ));
            state.all_succeeded = false;
            state
                .failed_commands
                .push("pacman -Syu --noconfirm".to_string());
            state.pacman_succeeded = Some(false);
        }
    }
}

/// What: Refresh sudo timestamp to allow AUR helper to use sudo without password prompt.
///
/// Inputs:
/// - `password`: Optional sudo password to use for refresh.
/// - `write_log`: Function to write log messages.
///
/// Output:
/// - None (no return value).
///
/// Details:
/// - Runs `sudo -S -v` with the password to refresh the sudo timestamp.
/// - This prevents a second password prompt when the AUR helper calls sudo internally.
/// - Only executes if a password is provided; silently does nothing if password is `None`.
/// - Logs the refresh operation to the log file.
#[cfg(not(target_os = "windows"))]
fn refresh_sudo_timestamp(password: Option<&str>, write_log: &(dyn Fn(&str) + Send + Sync)) {
    use std::process::Command;

    if let Some(pass) = password {
        let Ok(tool) = pacsea::logic::privilege::active_tool() else {
            return;
        };
        if let Some(warmup) = pacsea::logic::privilege::build_credential_warmup(tool, pass) {
            let _ = Command::new("bash")
                .arg("-c")
                .arg(&warmup)
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status();
            write_log(&format!(
                "Refreshed {} credential timestamp for AUR helper",
                tool.binary_name()
            ));
        }
    }
}

/// What: Execute AUR helper system update and update the state accordingly.
///
/// Inputs:
/// - `state`: Mutable reference to `UpdateState` to update.
/// - `log_file_path`: Path to the log file.
/// - `no_color`: If true, disables colored output.
/// - `write_log`: Function to write log messages.
///
/// Output:
/// - None (modifies state in place).
///
/// Details:
/// - Detects available AUR helper (paru/yay, prefers paru).
/// - Runs `{helper} -Sua --noconfirm` to update only AUR packages (official packages already updated by pacman).
/// - Updates state with success/failure status and failed packages.
/// - If no AUR helper is available, logs a warning and skips the update.
/// - Extracts failed package names from command output on failure.
/// - In interactive auth mode, stdin is inherited so the AUR helper's internal
///   sudo/doas can prompt via PAM.
#[cfg(not(target_os = "windows"))]
fn run_aur_update(
    state: &mut UpdateState,
    log_file_path: &Path,
    no_color: bool,
    interactive_auth: bool,
    write_log: &(dyn Fn(&str) + Send + Sync),
) {
    let aur_helper = utils::get_aur_helper();
    if let Some(helper) = aur_helper {
        state.aur_helper_name = Some(helper.to_string());
        println!(
            "\n{}",
            info_color(
                &i18n::t_fmt1("app.cli.update.aur_starting", helper),
                no_color
            )
        );
        write_log(&format!("Starting AUR update: {helper} -Sua --noconfirm"));

        let aur_result = run_command_with_logging(
            helper,
            &["-Sua", "--noconfirm"],
            log_file_path,
            None, // AUR helpers handle sudo internally, no password needed
            interactive_auth,
        );

        match aur_result {
            Ok((status, output)) => {
                if status.success() {
                    println!(
                        "{}",
                        success_color(
                            &i18n::t_fmt1("app.cli.update.aur_success", helper),
                            no_color
                        )
                    );
                    write_log(&format!(
                        "SUCCESS: {helper} -Sua --noconfirm completed successfully"
                    ));
                    state.aur_succeeded = Some(true);
                } else {
                    println!(
                        "{}",
                        error_color(&i18n::t_fmt1("app.cli.update.aur_failed", helper), no_color)
                    );
                    write_log(&format!(
                        "FAILED: {} -Sua --noconfirm failed with exit code {:?}",
                        helper,
                        status.code()
                    ));
                    let packages = extract_failed_packages(&output, helper);
                    state.failed_packages.extend(packages);
                    state.all_succeeded = false;
                    state
                        .failed_commands
                        .push(format!("{helper} -Sua --noconfirm"));
                    state.aur_succeeded = Some(false);
                }
            }
            Err(e) => {
                println!(
                    "{}",
                    error_color(
                        &i18n::t_fmt1("app.cli.update.aur_exec_failed", helper),
                        no_color
                    )
                );
                eprintln!(
                    "{}",
                    error_color(&i18n::t_fmt1("app.cli.update.error_prefix", &e), no_color)
                );
                write_log(&format!(
                    "FAILED: Could not execute {helper} -Sua --noconfirm: {e}"
                ));
                state.all_succeeded = false;
                state
                    .failed_commands
                    .push(format!("{helper} -Sua --noconfirm"));
                state.aur_succeeded = Some(false);
            }
        }
    } else {
        println!(
            "\n{}",
            warning_color(&i18n::t("app.cli.update.no_aur_helper"), no_color)
        );
        write_log("SKIPPED: No AUR helper (paru/yay) available");
    }
}

/// What: Display final update summary with status of all operations.
///
/// Inputs:
/// - `state`: Reference to `UpdateState` containing update results.
/// - `log_file_path`: Path to the log file.
/// - `no_color`: If true, disables colored output.
/// - `write_log`: Function to write log messages.
///
/// Output:
/// - None (prints to stdout and writes to log file).
///
/// Details:
/// - Shows individual status for pacman and AUR helper.
/// - Displays overall summary and failed packages if any.
/// - Shows log file location as clickable path using OSC 8 escape sequences.
/// - Uses colored output for success (green), error (red), info (cyan), and warning (yellow) messages.
/// - Logs summary information to the log file.
#[cfg(not(target_os = "windows"))]
fn display_update_summary(
    state: &UpdateState,
    log_file_path: &Path,
    no_color: bool,
    write_log: &(dyn Fn(&str) + Send + Sync),
) {
    // Final summary
    println!(
        "\n{}",
        info_color(&i18n::t("app.cli.update.separator"), no_color)
    );

    // Show individual status for pacman and AUR helper
    if state.pacman_succeeded == Some(true) {
        println!(
            "{}",
            success_color(&i18n::t("app.cli.update.pacman_success"), no_color)
        );
    } else if state.pacman_succeeded == Some(false) {
        println!(
            "{}",
            error_color(&i18n::t("app.cli.update.pacman_failed"), no_color)
        );
    }

    if let Some(helper) = &state.aur_helper_name {
        if state.aur_succeeded == Some(true) {
            println!(
                "{}",
                success_color(
                    &i18n::t_fmt1("app.cli.update.aur_success", helper),
                    no_color
                )
            );
        } else if state.aur_succeeded == Some(false) {
            println!(
                "{}",
                error_color(&i18n::t_fmt1("app.cli.update.aur_failed", helper), no_color)
            );
        }
    }

    // Show overall summary
    if state.all_succeeded {
        println!(
            "\n{}",
            success_color(&i18n::t("app.cli.update.all_success"), no_color)
        );
        write_log("SUMMARY: All updates completed successfully");
    } else {
        println!(
            "\n{}",
            error_color(&i18n::t("app.cli.update.completed_with_errors"), no_color)
        );

        // Clear failure summary
        println!(
            "\n{}",
            info_color(&i18n::t("app.cli.update.failure_summary"), no_color)
        );

        // Show what failed
        if state.pacman_succeeded == Some(false) {
            println!(
                "  {} {}",
                error_color("", no_color),
                error_color(&i18n::t("app.cli.update.pacman_failed"), no_color)
            );
        }

        if let Some(helper) = &state.aur_helper_name {
            if state.aur_succeeded == Some(false) {
                println!(
                    "  {} {}",
                    error_color("", no_color),
                    error_color(&i18n::t_fmt1("app.cli.update.aur_failed", helper), no_color)
                );
            } else if state.pacman_succeeded == Some(false) {
                println!(
                    "  {} {}",
                    warning_color("", no_color),
                    warning_color(
                        &i18n::t("app.cli.update.aur_skipped_pacman_failed"),
                        no_color
                    )
                );
            }
        }

        // Show failed commands
        if !state.failed_commands.is_empty() {
            println!(
                "\n{}",
                warning_color(&i18n::t("app.cli.update.failed_commands"), no_color)
            );
            for cmd in &state.failed_commands {
                println!("  - {}", error_color(cmd, no_color));
            }
        }

        // Show failed packages
        if !state.failed_packages.is_empty() {
            println!(
                "\n{}",
                warning_color(&i18n::t("app.cli.update.failed_packages"), no_color)
            );
            for pkg in &state.failed_packages {
                println!("  - {}", error_color(pkg, no_color));
            }
            write_log(&i18n::t_fmt1(
                "app.cli.update.failed_packages_log",
                format!("{:?}", state.failed_packages),
            ));
        }

        write_log(&format!(
            "SUMMARY: Update failed. Failed commands: {:?}",
            state.failed_commands
        ));
    }
    let log_file_format = i18n::t("app.cli.update.log_file");
    let clickable_path = format_clickable_path(log_file_path);
    // Replace {} placeholder with clickable path
    let log_file_message = log_file_format.replace("{}", &clickable_path);
    println!("{log_file_message}");
    write_log(&format!(
        "Update process finished. Log file: {}",
        log_file_path.display()
    ));
}

/// What: Handle system update by running pacman and AUR helper updates, logging results.
///
/// Inputs:
/// - `no_color`: If true, disables colored output.
///
/// Output:
/// - Exits the process with appropriate exit code.
///
/// Details:
/// - Runs `sudo pacman -Syu --noconfirm` first to update official packages.
/// - Then runs `yay -Sua --noconfirm` or `paru -Sua --noconfirm` (prefers paru) if available.
/// - AUR update is skipped if pacman update failed.
/// - Displays update progress output in real-time to the terminal.
/// - Logs all command output and status messages to `update.log` in the config logs directory.
/// - Informs user of final status and log file path.
/// - Uses colored output for success (green), error (red), info (cyan), and warning (yellow) messages.
#[cfg(not(target_os = "windows"))]
pub fn handle_update(no_color: bool) -> ! {
    tracing::info!("System update requested from CLI");

    // Get logs directory and create update.log path
    let logs_dir = theme::logs_dir();
    let log_file_path = logs_dir.join("update.log");

    // Setup log file and get write_log closure
    let write_log = setup_log_file(&log_file_path);

    // Prompt for password and validate it
    let password = prompt_and_validate_password(&*write_log);

    // Resolve whether we're in interactive auth mode (fingerprint / PAM direct)
    let settings = theme::settings();
    let interactive_auth = pacsea::logic::password::resolve_auth_mode(&settings)
        == pacsea::logic::privilege::AuthMode::Interactive;
    let readiness = pacsea::logic::long_run_auth::evaluate_long_run_auth_readiness(&settings);
    if readiness.should_warn {
        println!(
            "{}",
            warning_color(&i18n::t("app.cli.update.long_run_auth_warning"), no_color)
        );
        write_log("WARN: long-run auth readiness indicates possible mid-run re-auth prompt");
    }

    // Initialize update state
    let mut state = UpdateState::new();

    // Step 1: Update pacman (sudo pacman -Syu --noconfirm)
    run_pacman_update(
        &mut state,
        &log_file_path,
        password.as_deref(),
        no_color,
        interactive_auth,
        &*write_log,
    );

    // Refresh sudo timestamp after pacman command so AUR helper can use it
    // Skip in interactive mode — the privilege tool manages its own credential cache.
    if !interactive_auth {
        refresh_sudo_timestamp(password.as_deref(), &*write_log);
    }

    // Step 2: Update AUR packages (yay/paru -Sua --noconfirm) only if pacman succeeded
    if state.pacman_succeeded == Some(true) {
        run_aur_update(
            &mut state,
            &log_file_path,
            no_color,
            interactive_auth,
            &*write_log,
        );
    } else {
        println!(
            "\n{}",
            warning_color(
                &i18n::t("app.cli.update.aur_skipped_pacman_failed"),
                no_color
            )
        );
        write_log("SKIPPED: AUR update skipped because pacman update failed");
    }

    // Display final summary
    display_update_summary(&state, &log_file_path, no_color, &*write_log);

    // Exit with appropriate code
    if state.all_succeeded {
        tracing::info!("System update completed successfully");
        std::process::exit(0);
    } else {
        tracing::error!("System update completed with errors");
        std::process::exit(1);
    }
}