cleansys-core 0.6.6

Shared core logic for CleanSys — cleaners, domain model, and utilities shared by the TUI and GUI
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
use anyhow::Result;
#[cfg(target_os = "linux")]
use log::info;
use log::{debug, warn};
use std::path::Path;
use std::process::Command;

use crate::cleaners::cleaned_item::{CleanedItem, CleanerFn, CleaningResult, RunOptions};
#[cfg(any(target_os = "macos", target_os = "windows"))]
use crate::cleaners::platform;
#[cfg(target_os = "linux")]
use crate::utils::print_warning;
use crate::utils::{confirm, execute_with_sudo, format_size, get_size, print_error, print_success};

/// Information about a system cleaner.
pub struct CleanerInfo {
    /// The name of the cleaner.
    pub name: &'static str,
    /// A description of what the cleaner does.
    pub description: &'static str,
    /// The function that performs the cleaning operation.
    pub function: CleanerFn,
    /// Whether this specific cleaner needs root/Administrator privileges.
    ///
    /// Unlike Linux (where every system-level path needs root), not every
    /// "system cleaner" needs elevated privileges on every platform —
    /// notably Homebrew on macOS must **not** be run as root. This is
    /// declared per-cleaner rather than assumed true for the whole category.
    pub requires_root: bool,
}

/// Shorthand for a [`CleanerInfo`] entry. Collapses the repeated
/// `CleanerInfo { name, description, function, requires_root }` struct
/// literal (identical shape across all ~14 entries spread over the
/// Linux/macOS/Windows cleaner lists below) down to a single line per
/// cleaner.
macro_rules! cleaner {
    ($name:literal, $description:literal, $function:expr, requires_root: $root:literal) => {
        CleanerInfo {
            name: $name,
            description: $description,
            function: $function,
            requires_root: $root,
        }
    };
}

/// Lists all available system cleaners with their descriptions.
pub fn list_cleaners() -> Vec<String> {
    get_cleaners()
        .iter()
        .map(|c| format!("{}: {}", c.name, c.description))
        .collect()
}

/// Returns the system cleaners applicable to the current platform.
///
/// Unlike the user-level cleaners (which check OS-appropriate paths behind a
/// single shared list), system cleaners differ enough in *mechanism*
/// (apt/pacman/dnf on Linux vs. Homebrew on macOS vs. no equivalent concept
/// on Windows) that each platform gets its own cleaner list.
pub fn get_cleaners() -> Vec<CleanerInfo> {
    #[cfg(target_os = "linux")]
    {
        linux_cleaners()
    }
    #[cfg(target_os = "macos")]
    {
        macos_cleaners()
    }
    #[cfg(target_os = "windows")]
    {
        windows_cleaners()
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        Vec::new()
    }
}

/// Runs all system cleaners.
pub fn run_all(skip_confirmation: bool) -> Result<()> {
    let cleaners = get_cleaners();
    let mut total_saved: u64 = 0;
    let opts = if skip_confirmation {
        RunOptions::execute()
    } else {
        RunOptions::execute_with_confirmation()
    };

    for cleaner in cleaners {
        if skip_confirmation || confirm(&format!("Run '{}'?", cleaner.name), true)? {
            match (cleaner.function)(opts) {
                Ok(result) => {
                    total_saved += result.total_bytes;
                    print_success(&format!(
                        "{} completed: freed {} across {} item(s)",
                        cleaner.name,
                        format_size(result.total_bytes),
                        result.item_count()
                    ));
                }
                Err(err) => {
                    print_error(&format!("Error in {}: {}", cleaner.name, err));
                }
            }
        }
    }

    print_success(&format!("Total space freed: {}", format_size(total_saved)));
    Ok(())
}

/// Run a privileged command via [`execute_with_sudo`] and treat a non-zero
/// exit as a genuine failure (propagated as an `Err`) rather than silently
/// logging a `warn!()` and reporting success anyway.
///
/// This is the shared implementation behind every `measure_around`/
/// `measure_and_remove` closure below that shells out to a package manager
/// or system utility (`apt-get clean`, `pacman -Sc`, `dnf clean all`,
/// `journalctl --vacuum-time`, `updatedb`, ...). Before this helper existed,
/// each call site duplicated the same "warn on failure, then report success
/// anyway" boilerplate, which meant a *real* failure (permission denied,
/// binary missing a required flag, disk full, ...) was indistinguishable
/// from "nothing needed cleaning" — both silently produced a 0-byte,
/// no-error result. Bailing here makes real failures visible as an actual
/// ❌ error in the TUI/GUI instead.
fn run_sudo_step(label: &str, command: &str, args: &[&str]) -> Result<bool> {
    let output = execute_with_sudo(command, args)?;
    if !output.status.success() {
        anyhow::bail!(
            "failed to clean {label}: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(true)
}

/// Measure the real size of `path` before and after calling `action`, and
/// record the actual bytes freed (never an estimate/guess) as a
/// [`CleanedItem`] in `result` if anything was actually freed.
///
/// In [`RunOptions::preview`] mode, `action` (which typically shells out to a
/// mutating command like `apt-get clean`) is never invoked; instead the
/// entire pre-existing size of `path` is reported as the projected amount
/// that a real run would free.
fn measure_around<F>(
    result: &mut CleaningResult,
    path: &Path,
    label: &str,
    opts: RunOptions,
    action: F,
) -> Result<()>
where
    F: FnOnce() -> Result<bool>,
{
    let before = get_size(&path.to_string_lossy()).unwrap_or(0);

    if opts.dry_run {
        if before > 0 {
            result.add_item(CleanedItem::directory(path.to_path_buf(), before, label));
        }
        return Ok(());
    }

    let succeeded = action()?;
    if !succeeded {
        return Ok(());
    }
    let after = get_size(&path.to_string_lossy()).unwrap_or(before);
    let freed = before.saturating_sub(after);

    if freed > 0 {
        print_success(&format!("{label}: freed {}", format_size(freed)));
        result.add_item(CleanedItem::directory(path.to_path_buf(), freed, label));
    }

    Ok(())
}

/// Measure, and if not in preview mode remove, the contents of a single
/// path (file or whole directory tree) — the common pattern shared by most
/// "rm -rf $path/*" style system cleaners.
fn measure_and_remove(
    result: &mut CleaningResult,
    path: &Path,
    label: &str,
    opts: RunOptions,
    remove: impl FnOnce() -> Result<std::process::Output>,
) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }
    let size = get_size(&path.to_string_lossy())?;
    if size == 0 {
        return Ok(());
    }

    if opts.dry_run {
        result.add_item(CleanedItem::directory(path.to_path_buf(), size, label));
        return Ok(());
    }

    if !opts.skip_confirmation
        && !confirm(
            &format!("Clean {label} ({} to be freed)?", format_size(size)),
            true,
        )?
    {
        return Ok(());
    }

    match remove() {
        Ok(out) if out.status.success() => {
            print_success(&format!("Cleaned {label} ({})", format_size(size)));
            result.add_item(CleanedItem::directory(path.to_path_buf(), size, label));
        }
        Ok(_) => warn!("Failed to clean {label}"),
        Err(e) => warn!("Failed to execute cleanup for {label}: {e}"),
    }

    Ok(())
}

// ── Linux ────────────────────────────────────────────────────────────────────

#[cfg(target_os = "linux")]
fn linux_cleaners() -> Vec<CleanerInfo> {
    vec![
        cleaner!(
            "Package Manager Caches",
            "Clean package manager caches (apt, pacman, dnf)",
            clean_package_caches,
            requires_root: true
        ),
        cleaner!(
            "System Logs",
            "Clean rotated system logs and vacuum the systemd journal",
            clean_system_logs,
            requires_root: true
        ),
        cleaner!(
            "System Caches",
            "Clean system-wide cache directories (fontconfig, man, ldconfig)",
            clean_system_caches,
            requires_root: true
        ),
        cleaner!(
            "Temporary Files",
            "Clean old temporary files in /tmp and /var/tmp",
            clean_temp_files,
            requires_root: true
        ),
        cleaner!(
            "Old Kernels",
            "Remove old unused kernels (requires purge-old-kernels)",
            clean_old_kernels,
            requires_root: true
        ),
        cleaner!(
            "Crash Reports",
            "Remove system crash reports and core dumps",
            clean_crash_reports,
            requires_root: true
        ),
    ]
}

#[cfg(target_os = "linux")]
fn clean_package_caches(opts: RunOptions) -> Result<CleaningResult> {
    let mut result = CleaningResult::new();
    info!("Starting package cache cleaning...");

    // NOTE: this used to hard-require the whole process to already be
    // running as root (`check_root()`) before attempting anything, which
    // defeated the sudo-password-elevation flow entirely (GUI/TUI never run
    // the process itself as root — they elevate individual commands via
    // `execute_with_sudo`, which already handles both the "already root" and
    // "not root, use sudo" cases below). Removed; each package manager
    // invocation is elevated on its own via `execute_with_sudo`.

    if Path::new("/usr/bin/apt-get").exists() || Path::new("/usr/bin/apt").exists() {
        info!("Found APT package manager, cleaning cache...");
        measure_around(
            &mut result,
            Path::new("/var/cache/apt/archives"),
            "APT cache",
            opts,
            || run_sudo_step("APT cache", "apt-get", &["clean"]),
        )?;
    }

    if Path::new("/usr/bin/pacman").exists() {
        info!("Found Pacman package manager, cleaning cache...");
        measure_around(
            &mut result,
            Path::new("/var/cache/pacman/pkg"),
            "Pacman cache",
            opts,
            || run_sudo_step("Pacman cache", "pacman", &["-Sc", "--noconfirm"]),
        )?;
    }

    if Path::new("/usr/bin/dnf").exists() {
        info!("Found DNF package manager, cleaning cache...");
        measure_around(
            &mut result,
            Path::new("/var/cache/dnf"),
            "DNF cache",
            opts,
            || run_sudo_step("DNF cache", "dnf", &["clean", "all"]),
        )?;
    }

    info!(
        "Package cache cleaning completed, freed: {}",
        format_size(result.total_bytes)
    );
    Ok(result)
}

#[cfg(target_os = "linux")]
fn clean_system_logs(opts: RunOptions) -> Result<CleaningResult> {
    let mut result = CleaningResult::new();
    let log_path = Path::new("/var/log");

    if log_path.exists() {
        // Measure just the rotated/compressed logs we're actually targeting,
        // not the whole of /var/log (which includes live logs we never touch).
        let mut size_to_clean = 0u64;
        if let Ok(entries) = std::fs::read_dir(log_path) {
            for entry in entries.flatten() {
                let file_path = entry.path();
                let filename = file_path.file_name().unwrap_or_default().to_string_lossy();
                if file_path.is_file()
                    && (filename.ends_with(".gz")
                        || filename.ends_with(".old")
                        || filename.contains(".1")
                        || filename.contains(".2"))
                {
                    size_to_clean += std::fs::metadata(&file_path).map(|m| m.len()).unwrap_or(0);
                }
            }
        }

        if size_to_clean > 0 {
            if opts.dry_run {
                result.add_item(CleanedItem::directory(
                    log_path.to_path_buf(),
                    size_to_clean,
                    "rotated system logs",
                ));
            } else if opts.skip_confirmation
                || confirm(
                    &format!(
                        "Clean old logs in /var/log ({} to be freed)?",
                        format_size(size_to_clean)
                    ),
                    true,
                )?
            {
                let output = execute_with_sudo(
                    "find",
                    &[
                        "/var/log", "-type", "f", "-name", "*.gz", "-o", "-name", "*.old", "-o",
                        "-name", "*.1", "-o", "-name", "*.2", "-o", "-name", "*.3", "-o", "-name",
                        "*.4", "-delete",
                    ],
                )?;

                if output.status.success() {
                    print_success(&format!(
                        "Cleaned old logs in /var/log ({})",
                        format_size(size_to_clean)
                    ));
                    result.add_item(CleanedItem::directory(
                        log_path.to_path_buf(),
                        size_to_clean,
                        "rotated system logs",
                    ));
                } else {
                    print_error("Failed to clean logs in /var/log");
                }
            } else {
                debug!("No old logs found in /var/log");
            }
        }
    }

    // Vacuum the systemd journal, measuring the real size before/after.
    let has_journalctl = Command::new("which")
        .arg("journalctl")
        .output()?
        .status
        .success();

    if has_journalctl {
        if opts.dry_run {
            let before = get_size("/var/log/journal").unwrap_or(0);
            if before > 0 {
                result.add_item(CleanedItem::directory(
                    Path::new("/var/log/journal").to_path_buf(),
                    before,
                    "systemd journal",
                ));
            }
        } else if opts.skip_confirmation || confirm("Vacuum system journal logs?", true)? {
            measure_around(
                &mut result,
                Path::new("/var/log/journal"),
                "systemd journal",
                opts,
                || run_sudo_step("systemd journal", "journalctl", &["--vacuum-time=7d"]),
            )?;
        }
    }

    Ok(result)
}

#[cfg(target_os = "linux")]
fn clean_system_caches(opts: RunOptions) -> Result<CleaningResult> {
    let mut result = CleaningResult::new();
    let cache_paths = ["/var/cache/fontconfig", "/var/cache/man"];

    for cache_path in cache_paths {
        measure_and_remove(&mut result, Path::new(cache_path), cache_path, opts, || {
            execute_with_sudo("sh", &["-c", &format!("rm -rf {cache_path}/*")])
        })?;
    }

    if !opts.dry_run {
        let has_updatedb = Command::new("which")
            .arg("updatedb")
            .output()?
            .status
            .success();
        if has_updatedb && (opts.skip_confirmation || confirm("Update locate database?", true)?) {
            let output = execute_with_sudo("updatedb", &[])?;
            if output.status.success() {
                print_success("Updated locate database");
            } else {
                print_error("Failed to update locate database");
            }
        }
    }

    Ok(result)
}

#[cfg(target_os = "linux")]
fn clean_temp_files(opts: RunOptions) -> Result<CleaningResult> {
    let mut result = CleaningResult::new();

    for temp_path in ["/tmp", "/var/tmp"] {
        let path = Path::new(temp_path);
        if !path.exists() {
            continue;
        }

        // Only target files not accessed in the last day, matching the
        // previous behaviour, but measure real freed bytes via before/after
        // rather than parsing `du` output from a slow per-file `find -exec`.
        let before = get_size(temp_path).unwrap_or(0);
        let has_old_files = Command::new("find")
            .args([temp_path, "-type", "f", "-atime", "+1", "-print", "-quit"])
            .output()
            .map(|o| !o.stdout.is_empty())
            .unwrap_or(false);

        if !has_old_files {
            debug!("No old temporary files found in {temp_path}");
            continue;
        }

        if opts.dry_run {
            if before > 0 {
                result.add_item(CleanedItem::directory(
                    path.to_path_buf(),
                    before,
                    temp_path,
                ));
            }
            continue;
        }

        if opts.skip_confirmation
            || confirm(&format!("Clean old temporary files in {temp_path}?"), true)?
        {
            let output = execute_with_sudo(
                "find",
                &[temp_path, "-type", "f", "-atime", "+1", "-delete"],
            )?;

            if output.status.success() {
                let after = get_size(temp_path).unwrap_or(before);
                let freed = before.saturating_sub(after);
                if freed > 0 {
                    print_success(&format!(
                        "Cleaned old temporary files in {temp_path} ({})",
                        format_size(freed)
                    ));
                    result.add_item(CleanedItem::directory(path.to_path_buf(), freed, temp_path));
                }
            } else {
                print_error(&format!("Failed to clean temporary files in {temp_path}"));
            }
        }
    }

    Ok(result)
}

#[cfg(target_os = "linux")]
fn clean_old_kernels(opts: RunOptions) -> Result<CleaningResult> {
    let mut result = CleaningResult::new();

    if !(Command::new("which").arg("apt").output()?.status.success()
        && Command::new("which").arg("dpkg").output()?.status.success())
    {
        return Ok(result);
    }

    let output = Command::new("dpkg")
        .args(["-l", "linux-image-*"])
        .output()?;
    let installed_kernels = String::from_utf8_lossy(&output.stdout);
    let kernel_count = installed_kernels
        .lines()
        .filter(|l| l.contains("linux-image-") && l.starts_with("ii"))
        .count();
    debug!("Found {kernel_count} installed kernels");

    if kernel_count <= 2 {
        debug!("Not enough kernels installed to clean");
        return Ok(result);
    }

    if !Command::new("which")
        .arg("purge-old-kernels")
        .output()?
        .status
        .success()
    {
        print_warning(
            "purge-old-kernels not found. Install the byobu package for safer kernel cleanup.",
        );
        return Ok(result);
    }

    if opts.dry_run {
        let before = get_size("/boot").unwrap_or(0);
        if before > 0 {
            result.add_item(CleanedItem::directory(
                Path::new("/boot").to_path_buf(),
                before,
                "old kernels",
            ));
        }
        return Ok(result);
    }

    if opts.skip_confirmation
        || confirm(
            &format!(
                "Remove old kernels ({} installed, keeping 1)?",
                kernel_count
            ),
            true,
        )?
    {
        measure_around(&mut result, Path::new("/boot"), "old kernels", opts, || {
            run_sudo_step("old kernels", "purge-old-kernels", &["--keep", "1"])
        })?;
    }

    Ok(result)
}

#[cfg(target_os = "linux")]
fn clean_crash_reports(opts: RunOptions) -> Result<CleaningResult> {
    let mut result = CleaningResult::new();

    for crash_path in ["/var/crash", "/var/lib/systemd/coredump"] {
        measure_and_remove(&mut result, Path::new(crash_path), crash_path, opts, || {
            execute_with_sudo("sh", &["-c", &format!("rm -rf {crash_path}/*")])
        })?;
    }

    Ok(result)
}

// ── macOS ────────────────────────────────────────────────────────────────────

#[cfg(target_os = "macos")]
fn macos_cleaners() -> Vec<CleanerInfo> {
    vec![
        // Homebrew must NOT be run as root/sudo.
        cleaner!(
            "Homebrew Cache",
            "Clean the Homebrew download cache (brew cleanup)",
            clean_homebrew_cache,
            requires_root: false
        ),
        cleaner!(
            "Xcode Derived Data",
            "Clean Xcode DerivedData build caches (~/Library/Developer/Xcode/DerivedData)",
            clean_xcode_derived_data,
            requires_root: false
        ),
        cleaner!(
            "iOS Simulator Caches",
            "Clean unavailable iOS/watchOS/tvOS Simulator devices and their caches",
            clean_ios_simulator_caches,
            requires_root: false
        ),
        cleaner!(
            "System Logs",
            "Remove old rotated system logs",
            clean_system_logs,
            requires_root: true
        ),
        cleaner!(
            "Crash Reports",
            "Remove system diagnostic/crash reports",
            clean_crash_reports,
            requires_root: true
        ),
    ]
}

#[cfg(target_os = "macos")]
fn clean_homebrew_cache(opts: RunOptions) -> Result<CleaningResult> {
    let mut result = CleaningResult::new();

    if Command::new("which")
        .arg("brew")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
    {
        let cache_dir_output = Command::new("brew").arg("--cache").output()?;
        let cache_dir = String::from_utf8_lossy(&cache_dir_output.stdout)
            .trim()
            .to_string();
        let cache_path = Path::new(&cache_dir);

        if cache_path.exists() {
            if opts.dry_run {
                let before = get_size(&cache_dir).unwrap_or(0);
                if before > 0 {
                    result.add_item(CleanedItem::directory(
                        cache_path.to_path_buf(),
                        before,
                        "Homebrew cache",
                    ));
                }
            } else if opts.skip_confirmation
                || confirm("Clean Homebrew cache (brew cleanup)?", true)?
            {
                measure_around(&mut result, cache_path, "Homebrew cache", opts, || {
                    let output = Command::new("brew").args(["cleanup", "-s"]).output()?;
                    if !output.status.success() {
                        anyhow::bail!(
                            "brew cleanup failed: {}",
                            String::from_utf8_lossy(&output.stderr).trim()
                        );
                    }
                    Ok(true)
                })?;
            }
        }
    } else {
        debug!("Homebrew not installed — skipping Homebrew cache cleaner");
    }

    Ok(result)
}

/// Xcode's build system cache — regenerated automatically on next build, and
/// commonly grows into tens of GB over time. Safe to delete wholesale.
#[cfg(target_os = "macos")]
fn clean_xcode_derived_data(opts: RunOptions) -> Result<CleaningResult> {
    let mut result = CleaningResult::new();
    let Some(home) = platform::home_dir() else {
        return Ok(result);
    };
    let path = home.join("Library/Developer/Xcode/DerivedData");

    if path.exists() {
        let size = get_size(&path.to_string_lossy())?;
        if size == 0 {
            return Ok(result);
        }

        if opts.dry_run {
            result.add_item(CleanedItem::directory(path, size, "Xcode DerivedData"));
            return Ok(result);
        }

        if opts.skip_confirmation
            || confirm(
                &format!(
                    "Clean Xcode DerivedData ({} to be freed)?",
                    format_size(size)
                ),
                true,
            )?
        {
            match std::fs::remove_dir_all(&path) {
                Ok(()) => {
                    std::fs::create_dir_all(&path).ok();
                    print_success(&format!(
                        "Cleaned Xcode DerivedData ({})",
                        format_size(size)
                    ));
                    result.add_item(CleanedItem::directory(path, size, "Xcode DerivedData"));
                }
                Err(e) => warn!("Failed to clean Xcode DerivedData: {e}"),
            }
        }
    }

    Ok(result)
}

/// Removes unavailable (deleted-device-family) iOS/watchOS/tvOS Simulator
/// runtimes' caches via `xcrun simctl delete unavailable`, then measures the
/// Simulator caches directory before/after.
#[cfg(target_os = "macos")]
fn clean_ios_simulator_caches(opts: RunOptions) -> Result<CleaningResult> {
    let mut result = CleaningResult::new();
    let Some(home) = platform::home_dir() else {
        return Ok(result);
    };
    let caches_path = home.join("Library/Developer/CoreSimulator/Caches");

    if !Command::new("which")
        .arg("xcrun")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
    {
        debug!("xcrun not found — skipping iOS Simulator cache cleaner");
        return Ok(result);
    }

    if caches_path.exists() {
        if opts.dry_run {
            let before = get_size(&caches_path.to_string_lossy()).unwrap_or(0);
            if before > 0 {
                result.add_item(CleanedItem::directory(
                    caches_path,
                    before,
                    "iOS Simulator caches",
                ));
            }
            return Ok(result);
        }

        if opts.skip_confirmation
            || confirm(
                "Delete unavailable Simulator devices and clean their caches?",
                true,
            )?
        {
            measure_around(
                &mut result,
                &caches_path,
                "iOS Simulator caches",
                opts,
                || {
                    let output = Command::new("xcrun")
                        .args(["simctl", "delete", "unavailable"])
                        .output()?;
                    if !output.status.success() {
                        anyhow::bail!(
                            "xcrun simctl delete unavailable failed: {}",
                            String::from_utf8_lossy(&output.stderr).trim()
                        );
                    }
                    Ok(true)
                },
            )?;
        }
    }

    Ok(result)
}

#[cfg(target_os = "macos")]
fn clean_system_logs(opts: RunOptions) -> Result<CleaningResult> {
    let mut result = CleaningResult::new();
    let log_path = Path::new("/private/var/log");

    if log_path.exists() {
        let mut size_to_clean = 0u64;
        if let Ok(entries) = std::fs::read_dir(log_path) {
            for entry in entries.flatten() {
                let file_path = entry.path();
                let filename = file_path.file_name().unwrap_or_default().to_string_lossy();
                if file_path.is_file() && (filename.ends_with(".gz") || filename.contains(".0")) {
                    size_to_clean += std::fs::metadata(&file_path).map(|m| m.len()).unwrap_or(0);
                }
            }
        }

        if size_to_clean > 0 {
            if opts.dry_run {
                result.add_item(CleanedItem::directory(
                    log_path.to_path_buf(),
                    size_to_clean,
                    "rotated system logs",
                ));
            } else if opts.skip_confirmation
                || confirm(
                    &format!(
                        "Clean old rotated logs in /private/var/log ({} to be freed)?",
                        format_size(size_to_clean)
                    ),
                    true,
                )?
            {
                let cleaned = run_sudo_step(
                    "rotated system logs",
                    "find",
                    &["/private/var/log", "-type", "f", "-name", "*.gz", "-delete"],
                )?;
                if cleaned {
                    print_success(&format!(
                        "Cleaned old rotated logs in /private/var/log ({})",
                        format_size(size_to_clean)
                    ));
                    result.add_item(CleanedItem::directory(
                        log_path.to_path_buf(),
                        size_to_clean,
                        "rotated system logs",
                    ));
                }
            }
        }
    }

    Ok(result)
}

#[cfg(target_os = "macos")]
fn clean_crash_reports(opts: RunOptions) -> Result<CleaningResult> {
    let mut result = CleaningResult::new();
    let paths = [
        "/Library/Logs/DiagnosticReports".to_string(),
        platform::home_dir()
            .map(|h| {
                h.join("Library/Logs/DiagnosticReports")
                    .to_string_lossy()
                    .to_string()
            })
            .unwrap_or_default(),
    ];

    for crash_path in paths {
        if crash_path.is_empty() {
            continue;
        }
        measure_and_remove(
            &mut result,
            Path::new(&crash_path),
            &crash_path,
            opts,
            || execute_with_sudo("sh", &["-c", &format!("rm -rf '{crash_path}'/*")]),
        )?;
    }

    Ok(result)
}

// ── Windows ──────────────────────────────────────────────────────────────────

#[cfg(target_os = "windows")]
fn windows_cleaners() -> Vec<CleanerInfo> {
    vec![
        cleaner!(
            "Windows Update Cache",
            "Clean the Windows Update download cache (requires Administrator)",
            clean_windows_update_cache,
            requires_root: true
        ),
        cleaner!(
            "System Temp Files",
            "Clean C:\\Windows\\Temp (requires Administrator)",
            clean_windows_system_temp,
            requires_root: true
        ),
        cleaner!(
            "Recycle Bin",
            "Empty the Recycle Bin for all drives (requires Administrator)",
            clean_recycle_bin,
            requires_root: false
        ),
    ]
}

#[cfg(target_os = "windows")]
fn windows_dir() -> Option<std::path::PathBuf> {
    std::env::var_os("SystemRoot").map(std::path::PathBuf::from)
}

#[cfg(target_os = "windows")]
fn clean_windows_update_cache(opts: RunOptions) -> Result<CleaningResult> {
    let mut result = CleaningResult::new();
    let Some(win_dir) = windows_dir() else {
        return Ok(result);
    };
    let path = win_dir.join("SoftwareDistribution").join("Download");

    if path.exists() {
        let size = get_size(&path.to_string_lossy())?;
        if size == 0 {
            return Ok(result);
        }

        if opts.dry_run {
            result.add_item(CleanedItem::directory(path, size, "Windows Update cache"));
            return Ok(result);
        }

        if !opts.skip_confirmation
            && !confirm(
                &format!(
                    "Clean Windows Update cache ({} to be freed)?",
                    format_size(size)
                ),
                true,
            )?
        {
            return Ok(result);
        }

        match std::fs::remove_dir_all(&path) {
            Ok(()) => {
                std::fs::create_dir_all(&path).ok();
                print_success(&format!(
                    "Cleaned Windows Update cache ({})",
                    format_size(size)
                ));
                result.add_item(CleanedItem::directory(path, size, "Windows Update cache"));
            }
            Err(e) => {
                return Err(anyhow::anyhow!(
                    "Failed to clean Windows Update cache: {e} (try running CleanSys as Administrator)"
                ));
            }
        }
    }

    Ok(result)
}

#[cfg(target_os = "windows")]
fn clean_windows_system_temp(opts: RunOptions) -> Result<CleaningResult> {
    let mut result = CleaningResult::new();
    let Some(win_dir) = windows_dir() else {
        return Ok(result);
    };
    let path = win_dir.join("Temp");

    if !path.exists() {
        return Ok(result);
    }

    let total_size = get_size(&path.to_string_lossy())?;
    if total_size == 0 {
        return Ok(result);
    }

    if opts.dry_run {
        result.add_item(CleanedItem::directory(
            path,
            total_size,
            "Windows system temp",
        ));
        return Ok(result);
    }

    if !opts.skip_confirmation
        && !confirm(
            &format!(
                "Clean C:\\Windows\\Temp ({} to be freed)?",
                format_size(total_size)
            ),
            true,
        )?
    {
        return Ok(result);
    }

    let mut freed = 0u64;
    let mut any_permission_denied = false;
    if let Ok(entries) = std::fs::read_dir(&path) {
        for entry in entries.flatten() {
            let entry_path = entry.path();
            let entry_size = get_size(&entry_path.to_string_lossy()).unwrap_or(0);
            let removal = if entry_path.is_dir() {
                std::fs::remove_dir_all(&entry_path)
            } else {
                std::fs::remove_file(&entry_path)
            };
            match removal {
                Ok(()) => freed += entry_size,
                Err(_) => any_permission_denied = true,
            }
        }
    }

    if freed > 0 {
        print_success(&format!(
            "Cleaned C:\\Windows\\Temp ({})",
            format_size(freed)
        ));
        result.add_item(CleanedItem::directory(path, freed, "Windows system temp"));
    } else if any_permission_denied {
        return Err(anyhow::anyhow!(
            "Could not clean C:\\Windows\\Temp — try running CleanSys as Administrator"
        ));
    }

    Ok(result)
}

/// Empty the Recycle Bin for all fixed drives via the Shell32
/// `SHEmptyRecycleBinW` API — the same call Explorer's own "Empty Recycle
/// Bin" menu item uses, so no elevated privileges are actually required for
/// the current user's own Recycle Bin (multi-user machines may still
/// restrict other users' bins, in which case the call simply reports 0
/// items freed for those).
#[cfg(target_os = "windows")]
fn clean_recycle_bin(opts: RunOptions) -> Result<CleaningResult> {
    let mut result = CleaningResult::new();

    // There is no cheap, official way to query the Recycle Bin's *current*
    // size before emptying it without walking every drive's hidden
    // `$Recycle.Bin` folder (which requires elevated access to enumerate
    // correctly per-SID); rather than mis-report a size, we surface the
    // fact that this happened via the item's label instead.
    if opts.dry_run {
        result.add_item(CleanedItem::directory(
            std::path::PathBuf::from("Recycle Bin"),
            0,
            "Recycle Bin (size unknown until emptied)",
        ));
        return Ok(result);
    }

    if !opts.skip_confirmation && !confirm("Empty the Recycle Bin?", true)? {
        return Ok(result);
    }

    match windows_shell::empty_recycle_bin() {
        Ok(()) => {
            print_success("Emptied the Recycle Bin");
            result.add_item(CleanedItem::directory(
                std::path::PathBuf::from("Recycle Bin"),
                0,
                "Recycle Bin",
            ));
        }
        Err(e) => warn!("Failed to empty Recycle Bin: {e}"),
    }

    Ok(result)
}

/// Thin wrapper around the Win32 Shell API, isolated so the rest of this
/// module never has to deal with raw FFI directly.
#[cfg(target_os = "windows")]
mod windows_shell {
    use anyhow::Result;
    use windows::Win32::Foundation::HWND;
    use windows::Win32::UI::Shell::{
        SHEmptyRecycleBinW, SHERB_NOCONFIRMATION, SHERB_NOPROGRESSUI, SHERB_NOSOUND,
    };

    /// Empty the Recycle Bin for every drive, silently (no confirmation
    /// dialog, no progress UI, no sound — CleanSys already asked the user).
    pub fn empty_recycle_bin() -> Result<()> {
        // SAFETY: `SHEmptyRecycleBinW(None, None, flags)` empties the
        // Recycle Bin for *all* drives when both the window handle and root
        // path are null, which is exactly the documented, supported usage.
        let result = unsafe {
            SHEmptyRecycleBinW(
                Some(HWND(std::ptr::null_mut())),
                None,
                SHERB_NOCONFIRMATION | SHERB_NOPROGRESSUI | SHERB_NOSOUND,
            )
        };
        result.map_err(|e| anyhow::anyhow!("SHEmptyRecycleBinW failed: {e}"))
    }
}

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

    /// Regression test for the `run_sudo_step` helper extracted from the
    /// ~7 duplicated "run a privileged command, warn+swallow on failure"
    /// blocks: a failing command must now propagate as a real `Err` (so the
    /// GUI/TUI can show it) instead of being silently reported as success
    /// with nothing cleaned. `false` always exits non-zero regardless of
    /// whether this runs as root or via `sudo -n`/`sudo -S`, so this is
    /// deterministic in CI and on a developer machine alike.
    #[cfg(unix)]
    #[test]
    fn run_sudo_step_propagates_command_failure_as_err() {
        let result = run_sudo_step("test step", "false", &[]);
        let err = result.expect_err("a failing command must produce Err, not Ok(false)");
        assert!(
            err.to_string().contains("test step"),
            "error message should include the step's label: {err}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn run_sudo_step_errors_on_missing_binary() {
        // A nonexistent command must surface as an Err either way: as a
        // spawn failure if already root (direct exec), or as a non-zero
        // exit from sudo itself failing to run it otherwise — never a
        // silent Ok(false).
        let result = run_sudo_step("test step", "definitely-not-a-real-command-12345", &[]);
        assert!(result.is_err());
    }

    #[test]
    fn get_cleaners_returns_platform_appropriate_list() {
        let cleaners = get_cleaners();
        // Every currently-supported platform (linux/macos/windows) should
        // return a non-empty list; unknown platforms fall back to empty.
        #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
        assert!(!cleaners.is_empty());

        for cleaner in &cleaners {
            assert!(!cleaner.name.is_empty());
            assert!(!cleaner.description.is_empty());
        }
    }

    #[test]
    fn list_cleaners_formats_name_and_description() {
        for entry in list_cleaners() {
            assert!(entry.contains(':'));
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn linux_cleaners_includes_expected_names() {
        let names: Vec<&str> = linux_cleaners().iter().map(|c| c.name).collect();
        assert!(names.contains(&"Package Manager Caches"));
        assert!(names.contains(&"System Logs"));
        assert!(names.contains(&"Old Kernels"));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_cleaners_includes_expected_names() {
        let names: Vec<&str> = macos_cleaners().iter().map(|c| c.name).collect();
        assert!(names.contains(&"Homebrew Cache"));
        assert!(names.contains(&"Crash Reports"));
        assert!(names.contains(&"Xcode Derived Data"));
        assert!(names.contains(&"iOS Simulator Caches"));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn homebrew_cache_does_not_require_root() {
        // Regression guard: Homebrew explicitly refuses to run as root, so
        // this cleaner must never be lumped into the "needs sudo" bucket
        // the way Linux system cleaners are.
        let homebrew = macos_cleaners()
            .into_iter()
            .find(|c| c.name == "Homebrew Cache")
            .expect("Homebrew Cache cleaner should exist on macOS");
        assert!(!homebrew.requires_root);
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn xcode_cleaners_do_not_require_root() {
        let cleaners = macos_cleaners();
        for name in ["Xcode Derived Data", "iOS Simulator Caches"] {
            let c = cleaners.iter().find(|c| c.name == name).unwrap();
            assert!(!c.requires_root, "{name} should not require root");
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn linux_system_cleaners_all_require_root() {
        assert!(linux_cleaners().iter().all(|c| c.requires_root));
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn windows_cleaners_includes_expected_names() {
        let names: Vec<&str> = windows_cleaners().iter().map(|c| c.name).collect();
        assert!(names.contains(&"Windows Update Cache"));
        assert!(names.contains(&"Recycle Bin"));
    }
}