smirrors 0.1.0

Automatic mirror list updater for Linux distributions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
//! Command handlers for SMirrors CLI
//!
//! This module implements all CLI commands with complete functionality including
//! output formatting, user interactions, and error handling.

use super::args::{Cli, Commands, ConfigAction, OutputFormat, ServiceAction, SortBy};
use crate::config::Config;
use crate::core::{Mirror, MirrorTester, MirrorUpdater, TestResult, UpdateOptions};
use crate::distro::detect_handler;
use crate::storage::{BackupManager, Database, MirrorFilter, UpdateRecord};
use crate::utils::SMirrorsError;
use anyhow::{Context, Result};
use std::io::{self, Write};
use std::process::Command as ProcessCommand;
use std::sync::Arc;
use tracing::{debug, info};
use url::Url;

/// Main command dispatcher
///
/// Routes CLI commands to their respective handlers and manages
/// overall error handling and logging setup.
pub async fn handle_command(cli: Cli) -> Result<()> {
    // Initialize logging based on verbosity
    crate::utils::init_cli_logger(cli.log_level())?;

    debug!("Executing command: {:?}", cli.command);

    match cli.command {
        Commands::Test {
            count,
            format,
            success_only,
            sort,
        } => test_command(cli.config, count, format, success_only, sort).await,

        Commands::Update {
            dry_run,
            force,
            limit,
            yes,
        } => update_command(cli.config, dry_run, force, limit, yes).await,

        Commands::List {
            static_only,
            with_tests,
            format,
        } => list_command(cli.config, static_only, with_tests, format).await,

        Commands::Add {
            repo,
            url,
            skip_validation,
        } => add_command(cli.config, repo, url, skip_validation).await,

        Commands::Remove { mirror, yes } => remove_command(cli.config, mirror, yes).await,

        Commands::Tui => tui_command().await,

        Commands::Status { detailed, format } => status_command(detailed, format).await,

        Commands::History {
            count,
            format,
            success_only,
            failed_only,
        } => history_command(count, format, success_only, failed_only).await,

        Commands::Rollback {
            backup_id,
            yes,
            list,
        } => rollback_command(cli.config, backup_id, yes, list).await,

        Commands::Enable { now } => enable_command(now).await,

        Commands::Disable { stop } => disable_command(stop).await,

        Commands::Config { action } => config_command(cli.config, action).await,

        Commands::Init { force, skip_service } => init_command(force, skip_service).await,

        Commands::Service { action } => service_command(cli.config, action).await,
    }
}

/// Test mirrors without updating
async fn test_command(
    config_path: Option<std::path::PathBuf>,
    count: Option<usize>,
    format: OutputFormat,
    success_only: bool,
    sort: SortBy,
) -> Result<()> {
    info!("Starting mirror test");

    // Load configuration
    let config = load_config(config_path)?;

    // Detect distribution handler
    let handler = detect_handler()?;
    info!("Detected distribution: {}", handler.name());

    // Get available mirrors
    println!("Fetching available mirrors...");
    let mut mirrors = handler
        .get_available_mirrors()
        .await
        .context("Failed to fetch available mirrors")?;

    // Apply count limit if specified
    if let Some(limit) = count {
        mirrors.truncate(limit);
    }

    println!("Testing {} mirrors...", mirrors.len());

    // Create tester
    let tester = MirrorTester::from_config(&config)?;

    // Test mirrors with progress tracking
    let progress_callback = Arc::new(move |current: usize, total: usize, url: &str| {
        eprint!(
            "\rTesting mirrors: {}/{} - {}",
            current, total, url
        );
        let _ = io::stderr().flush();
    });

    let results = tester.test_all(mirrors, Some(progress_callback)).await;
    eprintln!(); // New line after progress

    // Filter results if needed
    let filtered_results: Vec<TestResult> = if success_only {
        results.into_iter().filter(|r| r.success).collect()
    } else {
        results
    };

    // Sort results
    let sorted_results = sort_test_results(filtered_results, sort);

    // Display results
    println!("\nTest Results:");
    println!("{}", format_test_results(&sorted_results, format));

    // Summary
    let successful = sorted_results.iter().filter(|r| r.success).count();
    let failed = sorted_results.len() - successful;

    println!("\nSummary:");
    println!("  Total:      {}", sorted_results.len());
    println!("  Successful: {}", successful);
    println!("  Failed:     {}", failed);

    Ok(())
}

/// Update mirror list
async fn update_command(
    config_path: Option<std::path::PathBuf>,
    dry_run: bool,
    force: bool,
    limit: Option<usize>,
    yes: bool,
) -> Result<()> {
    // Check for root privileges unless dry-run
    if !dry_run && !nix::unistd::geteuid().is_root() {
        return Err(SMirrorsError::PermissionDenied(
            "Updating mirror configuration requires root privileges. Try running with sudo"
                .to_string(),
        )
        .into());
    }

    info!("Starting mirror update");

    // Load configuration
    let config = load_config(config_path)?;

    // Detect distribution handler
    let handler = detect_handler()?;
    info!("Detected distribution: {}", handler.name());

    // Create updater (wrapping handler in Arc)
    let handler_arc: Arc<dyn crate::distro::DistroHandler> = handler.into();
    let updater = MirrorUpdater::new(config.clone(), handler_arc)?;

    // Prepare update options
    let options = UpdateOptions {
        dry_run,
        force,
        limit,
    };

    // Show warning and confirmation if not dry-run and not auto-confirmed
    if !dry_run && !yes {
        println!("\nWARNING: This will modify your system's package manager configuration.");
        println!("A backup will be created before making changes.");
        println!();

        if !prompt_confirmation("Do you want to continue?")? {
            println!("Update cancelled.");
            return Ok(());
        }
    }

    // Perform update
    println!("Updating mirrors...");
    let result = updater.update(&options).await?;

    // Display results
    if result.dry_run {
        println!("\n{} DRY RUN RESULTS {}", "=".repeat(25), "=".repeat(25));
    } else {
        println!("\n{} UPDATE RESULTS {}", "=".repeat(25), "=".repeat(25));
    }

    println!("Status:            {}", if result.success { "Success" } else { "Failed" });
    println!("Mirrors tested:    {}", result.mirrors_tested);
    println!("Mirrors selected:  {}", result.mirrors_selected);
    println!("Static mirrors:    {}", result.static_mirrors_count);

    if let Some(ref error) = result.error {
        println!("Error:             {}", error);
    }

    if result.success && !result.dry_run {
        println!("\n{} Mirror configuration updated successfully!", "");
        println!("Run 'sudo apt update' (or equivalent) to use the new mirrors.");

        // Save to database
        if let Ok(db) = get_database() {
            let _ = db.save_update_record(
                result.mirrors_selected as i64,
                true,
                None,
            );
        }
    } else if result.success && result.dry_run {
        println!("\n{} Dry run completed. Use --no-dry-run to apply changes.", "");
    }

    Ok(())
}

/// List current mirrors
async fn list_command(
    config_path: Option<std::path::PathBuf>,
    static_only: bool,
    with_tests: bool,
    format: OutputFormat,
) -> Result<()> {
    info!("Listing current mirrors");

    // Load configuration (in case we need it later)
    let _config = load_config(config_path)?;

    // Get mirrors from database or distro handler
    let mirrors = if with_tests {
        // Get from database with test results
        let db = get_database()?;
        let filter = MirrorFilter {
            static_only,
            tested_only: false,
            country: None,
            min_score: None,
        };
        db.get_mirrors(&filter)?
    } else {
        // Get from distro handler
        let handler = detect_handler()?;
        let mut mirrors = handler.get_current_mirrors()?;

        if static_only {
            mirrors.retain(|m| m.is_static);
        }

        mirrors
    };

    if mirrors.is_empty() {
        println!("No mirrors found.");
        return Ok(());
    }

    println!("Current Mirrors ({} total):", mirrors.len());
    println!("{}", format_mirrors(&mirrors, format, with_tests));

    Ok(())
}

/// Add a static mirror
async fn add_command(
    config_path: Option<std::path::PathBuf>,
    repo: Option<String>,
    url: String,
    skip_validation: bool,
) -> Result<()> {
    info!("Adding static mirror: {}", url);

    // Parse and validate URL
    let parsed_url = Url::parse(&url).context("Invalid URL format")?;

    // Validate URL reachability unless skipped
    if !skip_validation {
        print!("Validating mirror URL...");
        io::stdout().flush()?;

        if let Err(e) = crate::utils::check_url_reachable(&parsed_url).await {
            eprintln!(" Failed!");
            return Err(anyhow::anyhow!("Mirror URL is not reachable: {}", e));
        }

        println!(" OK");
    }

    // Load configuration
    let mut config = load_config(config_path.clone())?;

    // Generate repo name if not provided
    let repo_name = repo.unwrap_or_else(|| {
        parsed_url
            .host_str()
            .unwrap_or("mirror")
            .to_string()
    });

    // Check if already exists
    if config.static_mirrors.contains_key(&repo_name) {
        return Err(anyhow::anyhow!(
            "Static mirror '{}' already exists. Use remove first or choose a different name.",
            repo_name
        ));
    }

    // Add to configuration
    config.static_mirrors.insert(repo_name.clone(), url.clone());

    // Save configuration
    config.save().context("Failed to save configuration")?;

    println!("✓ Static mirror '{}' added successfully: {}", repo_name, url);

    Ok(())
}

/// Remove a mirror
async fn remove_command(
    config_path: Option<std::path::PathBuf>,
    mirror: String,
    yes: bool,
) -> Result<()> {
    info!("Removing mirror: {}", mirror);

    // Load configuration
    let mut config = load_config(config_path.clone())?;

    // Find mirror by name or URL
    let mirror_key = if config.static_mirrors.contains_key(&mirror) {
        mirror.clone()
    } else {
        // Try to find by URL
        config
            .static_mirrors
            .iter()
            .find(|(_, url)| url.as_str() == mirror)
            .map(|(name, _)| name.clone())
            .ok_or_else(|| anyhow::anyhow!("Mirror '{}' not found in static mirrors", mirror))?
    };

    let mirror_url = config.static_mirrors.get(&mirror_key).unwrap().clone();

    // Confirmation
    if !yes {
        println!("Mirror to remove:");
        println!("  Name: {}", mirror_key);
        println!("  URL:  {}", mirror_url);
        println!();

        if !prompt_confirmation("Are you sure you want to remove this mirror?")? {
            println!("Removal cancelled.");
            return Ok(());
        }
    }

    // Remove from configuration
    config.static_mirrors.remove(&mirror_key);

    // Save configuration
    config.save().context("Failed to save configuration")?;

    println!("✓ Static mirror '{}' removed successfully", mirror_key);

    Ok(())
}

/// Launch interactive TUI
async fn tui_command() -> Result<()> {
    // TUI is not yet implemented, show helpful message
    println!("Interactive TUI is not yet implemented.");
    println!();
    println!("In the meantime, you can use these commands:");
    println!("  smirrors test       - Test available mirrors");
    println!("  smirrors update     - Update mirror configuration");
    println!("  smirrors list       - List current mirrors");
    println!("  smirrors status     - Show service status");
    println!("  smirrors history    - View update history");
    println!();
    println!("Run 'smirrors --help' for more information.");

    Ok(())
}

/// Show service status
async fn status_command(detailed: bool, format: OutputFormat) -> Result<()> {
    info!("Checking service status");

    let service_status = get_systemd_service_status("smirrors.service")?;
    let timer_status = get_systemd_service_status("smirrors.timer")?;

    match format {
        OutputFormat::Json => {
            let json = serde_json::json!({
                "service": service_status,
                "timer": timer_status,
            });
            println!("{}", serde_json::to_string_pretty(&json)?);
        }
        _ => {
            println!("SMirrors Service Status:");
            println!();
            println!("Service: {}", service_status.active);
            println!("Timer:   {}", timer_status.active);
            println!();

            if detailed {
                println!("Detailed Service Status:");
                println!("{}", service_status.status_output);
                println!();
                println!("Detailed Timer Status:");
                println!("{}", timer_status.status_output);
            }

            // Show last update from database
            if let Ok(db) = get_database() {
                if let Ok(Some(last_update)) = db.get_latest_update() {
                    println!();
                    println!("Last Update:");
                    println!("  Time:            {}", last_update.updated_at.format("%Y-%m-%d %H:%M:%S UTC"));
                    println!("  Mirrors changed: {}", last_update.mirrors_changed);
                    println!("  Status:          {}", if last_update.success { "Success" } else { "Failed" });

                    if let Some(ref error) = last_update.error {
                        println!("  Error:           {}", error);
                    }
                }
            }
        }
    }

    Ok(())
}

/// View update history
async fn history_command(
    count: usize,
    format: OutputFormat,
    success_only: bool,
    failed_only: bool,
) -> Result<()> {
    info!("Retrieving update history");

    // Get database
    let db = get_database()?;

    // Fetch history
    let mut history = db.get_history(count)?;

    // Filter if needed
    if success_only {
        history.retain(|h| h.success);
    } else if failed_only {
        history.retain(|h| !h.success);
    }

    if history.is_empty() {
        println!("No update history found.");
        return Ok(());
    }

    println!("Update History ({} entries):", history.len());
    println!("{}", format_history(&history, format));

    Ok(())
}

/// Rollback to previous configuration
async fn rollback_command(
    config_path: Option<std::path::PathBuf>,
    backup_id: Option<String>,
    yes: bool,
    list: bool,
) -> Result<()> {
    // Check for root privileges
    if !nix::unistd::geteuid().is_root() {
        return Err(SMirrorsError::PermissionDenied(
            "Rollback requires root privileges. Try running with sudo".to_string(),
        )
        .into());
    }

    // Get backup manager
    let config = load_config(config_path)?;
    let backup_dir = Config::data_dir()?.join("backups");
    let backup_manager = BackupManager::new(&backup_dir, config.distro.backup_count)?;

    // If list flag is set, just list backups
    if list {
        let backups = backup_manager.list_backups()?;

        if backups.is_empty() {
            println!("No backups found.");
            return Ok(());
        }

        println!("Available Backups:");
        for backup in &backups {
            println!();
            println!("  ID:          {}", backup.id);
            println!("  Created:     {}", backup.created_at.format("%Y-%m-%d %H:%M:%S UTC"));
            println!("  Files:       {}", backup.file_count);
            println!("  Size:        {}", crate::utils::format_size(backup.total_size as usize));

            if let Some(ref desc) = backup.description {
                println!("  Description: {}", desc);
            }
        }

        return Ok(());
    }

    // Get backup to restore
    let target_backup = if let Some(id) = backup_id {
        id
    } else {
        backup_manager
            .get_latest_backup_id()?
            .ok_or_else(|| anyhow::anyhow!("No backups available to restore"))?
    };

    // Get backup info
    let backups = backup_manager.list_backups()?;
    let backup_info = backups
        .iter()
        .find(|b| b.id == target_backup)
        .ok_or_else(|| anyhow::anyhow!("Backup '{}' not found", target_backup))?;

    // Confirmation
    if !yes {
        println!("Backup to restore:");
        println!("  ID:      {}", backup_info.id);
        println!("  Created: {}", backup_info.created_at.format("%Y-%m-%d %H:%M:%S UTC"));
        println!("  Files:   {}", backup_info.file_count);
        println!();
        println!("WARNING: This will overwrite your current mirror configuration.");
        println!();

        if !prompt_confirmation("Do you want to continue?")? {
            println!("Rollback cancelled.");
            return Ok(());
        }
    }

    // Perform rollback
    println!("Restoring backup...");
    let restored_count = backup_manager.restore_backup(&target_backup, true)?;

    println!("✓ Successfully restored {} files from backup '{}'", restored_count, target_backup);
    println!("Run 'sudo apt update' (or equivalent) to use the restored mirrors.");

    // Log to database
    if let Ok(db) = get_database() {
        let _ = db.save_update_record(
            restored_count as i64,
            true,
            Some(format!("Rollback to backup {}", target_backup)),
        );
    }

    Ok(())
}

/// Enable automatic updates
async fn enable_command(now: bool) -> Result<()> {
    // Check for root privileges
    if !nix::unistd::geteuid().is_root() {
        return Err(SMirrorsError::PermissionDenied(
            "Enabling service requires root privileges. Try running with sudo".to_string(),
        )
        .into());
    }

    info!("Enabling SMirrors service");

    // Enable timer
    println!("Enabling SMirrors timer...");
    systemctl_command("enable", "smirrors.timer")?;

    // Start timer
    println!("Starting SMirrors timer...");
    systemctl_command("start", "smirrors.timer")?;

    println!("✓ SMirrors automatic updates enabled");

    // Start service immediately if requested
    if now {
        println!("Starting SMirrors service...");
        systemctl_command("start", "smirrors.service")?;
        println!("✓ SMirrors service started");
    }

    // Show timer status
    println!();
    let timer_status = get_systemd_service_status("smirrors.timer")?;
    println!("Timer status: {}", timer_status.active);

    Ok(())
}

/// Disable automatic updates
async fn disable_command(stop: bool) -> Result<()> {
    // Check for root privileges
    if !nix::unistd::geteuid().is_root() {
        return Err(SMirrorsError::PermissionDenied(
            "Disabling service requires root privileges. Try running with sudo".to_string(),
        )
        .into());
    }

    info!("Disabling SMirrors service");

    // Stop and disable timer
    println!("Stopping SMirrors timer...");
    systemctl_command("stop", "smirrors.timer")?;

    println!("Disabling SMirrors timer...");
    systemctl_command("disable", "smirrors.timer")?;

    println!("✓ SMirrors automatic updates disabled");

    // Stop service if requested
    if stop {
        println!("Stopping SMirrors service...");
        systemctl_command("stop", "smirrors.service")?;
        println!("✓ SMirrors service stopped");
    }

    Ok(())
}

/// Manage configuration
async fn config_command(
    config_path: Option<std::path::PathBuf>,
    action: Option<ConfigAction>,
) -> Result<()> {
    match action {
        None | Some(ConfigAction::Show { .. }) => {
            let raw = matches!(action, Some(ConfigAction::Show { raw: true, .. }));
            let section = match action {
                Some(ConfigAction::Show { section, .. }) => section,
                _ => None,
            };

            config_show(config_path, raw, section).await
        }
        Some(ConfigAction::Set { key, value }) => config_set(config_path, key, value).await,
        Some(ConfigAction::Get { key }) => config_get(config_path, key).await,
        Some(ConfigAction::Edit { validate }) => config_edit(config_path, validate).await,
        Some(ConfigAction::Validate { verbose }) => config_validate(config_path, verbose).await,
        Some(ConfigAction::Reset { section, yes }) => config_reset(config_path, section, yes).await,
    }
}

/// Show configuration
async fn config_show(
    config_path: Option<std::path::PathBuf>,
    raw: bool,
    section: Option<String>,
) -> Result<()> {
    let config = load_config(config_path)?;

    if raw {
        let toml = toml::to_string_pretty(&config)?;
        println!("{}", toml);
    } else if let Some(section_name) = section {
        match section_name.as_str() {
            "general" => println!("{:#?}", config.general),
            "testing" => println!("{:#?}", config.testing),
            "distro" => println!("{:#?}", config.distro),
            "logging" => println!("{:#?}", config.logging),
            "notifications" => println!("{:#?}", config.notifications),
            "static_mirrors" => println!("{:#?}", config.static_mirrors),
            _ => return Err(anyhow::anyhow!("Unknown section: {}", section_name)),
        }
    } else {
        println!("{:#?}", config);
    }

    Ok(())
}

/// Set configuration value
async fn config_set(
    config_path: Option<std::path::PathBuf>,
    key: String,
    value: String,
) -> Result<()> {
    let mut config = load_config(config_path.clone())?;

    config.set(&key, &value)?;

    config.save()?;

    println!("✓ Configuration updated: {} = {}", key, value);

    Ok(())
}

/// Get configuration value
async fn config_get(config_path: Option<std::path::PathBuf>, key: String) -> Result<()> {
    let config = load_config(config_path)?;

    if let Some(value) = config.get(&key) {
        println!("{}", value);
    } else {
        return Err(anyhow::anyhow!("Configuration key '{}' not found", key));
    }

    Ok(())
}

/// Edit configuration file
async fn config_edit(config_path: Option<std::path::PathBuf>, validate: bool) -> Result<()> {
    let config_file = config_path.unwrap_or_else(|| Config::config_path().unwrap());

    // Get editor from environment or use default
    let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vi".to_string());

    // Open editor
    let status = ProcessCommand::new(&editor)
        .arg(&config_file)
        .status()
        .with_context(|| format!("Failed to open editor '{}'", editor))?;

    if !status.success() {
        return Err(anyhow::anyhow!("Editor exited with non-zero status"));
    }

    // Validate if requested
    if validate {
        println!("Validating configuration...");
        match Config::load_from(&config_file) {
            Ok(_) => println!("✓ Configuration is valid"),
            Err(e) => {
                eprintln!("✗ Configuration validation failed: {}", e);
                return Err(e);
            }
        }
    }

    Ok(())
}

/// Validate configuration
async fn config_validate(config_path: Option<std::path::PathBuf>, verbose: bool) -> Result<()> {
    let config_file = config_path.unwrap_or_else(|| Config::config_path().unwrap());

    println!("Validating configuration at: {:?}", config_file);

    match Config::load_from(&config_file) {
        Ok(config) => {
            println!("✓ Configuration is valid");

            if verbose {
                println!();
                println!("Configuration details:");
                println!("{:#?}", config);
            }

            Ok(())
        }
        Err(e) => {
            eprintln!("✗ Configuration validation failed:");
            eprintln!("{}", e);
            Err(e)
        }
    }
}

/// Reset configuration
async fn config_reset(
    config_path: Option<std::path::PathBuf>,
    section: Option<String>,
    yes: bool,
) -> Result<()> {
    let mut config = load_config(config_path.clone())?;

    // Confirmation
    if !yes {
        let message = if let Some(ref s) = section {
            format!("Are you sure you want to reset the '{}' section to defaults?", s)
        } else {
            "Are you sure you want to reset ALL configuration to defaults?".to_string()
        };

        if !prompt_confirmation(&message)? {
            println!("Reset cancelled.");
            return Ok(());
        }
    }

    // Reset appropriate section or entire config
    if let Some(section_name) = section {
        match section_name.as_str() {
            "general" => config.general = Default::default(),
            "testing" => config.testing = Default::default(),
            "distro" => config.distro = Default::default(),
            "logging" => config.logging = Default::default(),
            "notifications" => config.notifications = Default::default(),
            "static_mirrors" => config.static_mirrors.clear(),
            _ => return Err(anyhow::anyhow!("Unknown section: {}", section_name)),
        }
        println!("✓ Section '{}' reset to defaults", section_name);
    } else {
        config = Config::default();
        println!("✓ All configuration reset to defaults");
    }

    config.save()?;

    Ok(())
}

/// Initialize SMirrors
async fn init_command(force: bool, skip_service: bool) -> Result<()> {
    info!("Initializing SMirrors");

    let is_root = nix::unistd::geteuid().is_root();

    // Create configuration
    let config_path = Config::config_path()?;

    if config_path.exists() && !force {
        println!("Configuration already exists at: {:?}", config_path);
        println!("Use --force to reinitialize.");
        return Ok(());
    }

    println!("Creating configuration...");
    let config = Config::default();
    config.save()?;
    println!("✓ Configuration created at: {:?}", config_path);

    // Create data directories
    println!("Creating data directories...");
    let data_dir = Config::data_dir()?;
    std::fs::create_dir_all(&data_dir)?;
    println!("✓ Data directory created at: {:?}", data_dir);

    // Create cache directory
    let cache_dir = Config::cache_dir()?;
    std::fs::create_dir_all(&cache_dir)?;
    println!("✓ Cache directory created at: {:?}", cache_dir);

    // Initialize database
    println!("Initializing database...");
    let db_path = data_dir.join("smirrors.db");
    let _db = Database::new(&db_path)?;
    println!("✓ Database initialized at: {:?}", db_path);

    // Install systemd service if root and not skipped
    if is_root && !skip_service {
        println!("Installing systemd service...");
        // This would require the service files to be present
        // For now, just show a message
        println!("ℹ  Systemd service installation not implemented yet.");
        println!("   Service files should be installed to /etc/systemd/system/");
    }

    println!();
    println!("✓ SMirrors initialization complete!");
    println!();
    println!("Next steps:");
    println!("  1. Review configuration: smirrors config show");
    println!("  2. Test mirrors: smirrors test");
    println!("  3. Update mirrors: sudo smirrors update");

    if is_root && !skip_service {
        println!("  4. Enable automatic updates: sudo smirrors enable");
    }

    Ok(())
}

/// Run as service (hidden command)
async fn service_command(
    config_path: Option<std::path::PathBuf>,
    action: ServiceAction,
) -> Result<()> {
    match action {
        ServiceAction::Run => {
            // This would run the service in foreground mode
            // Implementation would involve setting up a scheduler
            println!("Service mode not yet implemented");
            Ok(())
        }
        ServiceAction::Update => {
            // Perform a single update
            update_command(config_path, false, false, None, true).await
        }
    }
}

// =============================================================================
// Helper Functions
// =============================================================================

/// Load configuration from path or default location
fn load_config(config_path: Option<std::path::PathBuf>) -> Result<Config> {
    if let Some(path) = config_path {
        Config::load_from(&path)
    } else {
        Config::load()
    }
}

/// Get database instance
fn get_database() -> Result<Database> {
    let db_path = Config::data_dir()?.join("smirrors.db");
    Database::new(&db_path)
}

/// Prompt user for yes/no confirmation
fn prompt_confirmation(message: &str) -> Result<bool> {
    print!("{} [y/N] ", message);
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;

    Ok(input.trim().eq_ignore_ascii_case("y") || input.trim().eq_ignore_ascii_case("yes"))
}

/// Execute systemctl command
fn systemctl_command(action: &str, unit: &str) -> Result<()> {
    let output = ProcessCommand::new("systemctl")
        .arg(action)
        .arg(unit)
        .output()
        .context("Failed to execute systemctl")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(anyhow::anyhow!("systemctl {} {} failed: {}", action, unit, stderr));
    }

    Ok(())
}

/// Systemd service status
#[derive(Debug, Clone, serde::Serialize)]
struct ServiceStatus {
    active: String,
    status_output: String,
}

/// Get systemd service status
fn get_systemd_service_status(unit: &str) -> Result<ServiceStatus> {
    let output = ProcessCommand::new("systemctl")
        .arg("is-active")
        .arg(unit)
        .output()
        .context("Failed to check service status")?;

    let active = String::from_utf8_lossy(&output.stdout).trim().to_string();

    let status_output = ProcessCommand::new("systemctl")
        .arg("status")
        .arg(unit)
        .arg("--no-pager")
        .output()
        .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
        .unwrap_or_else(|_| "Unable to get status".to_string());

    Ok(ServiceStatus {
        active,
        status_output,
    })
}

/// Sort test results
fn sort_test_results(mut results: Vec<TestResult>, sort_by: SortBy) -> Vec<TestResult> {
    match sort_by {
        SortBy::Score => {
            results.sort_by(|a, b| {
                let score_a = a.score.unwrap_or(0.0);
                let score_b = b.score.unwrap_or(0.0);
                score_b.partial_cmp(&score_a).unwrap_or(std::cmp::Ordering::Equal)
            });
        }
        SortBy::Speed => {
            results.sort_by(|a, b| {
                let speed_a = a.speed.unwrap_or(0.0);
                let speed_b = b.speed.unwrap_or(0.0);
                speed_b.partial_cmp(&speed_a).unwrap_or(std::cmp::Ordering::Equal)
            });
        }
        SortBy::Latency => {
            results.sort_by(|a, b| {
                let lat_a = a.latency.map(|d| d.as_millis()).unwrap_or(u128::MAX);
                let lat_b = b.latency.map(|d| d.as_millis()).unwrap_or(u128::MAX);
                lat_a.cmp(&lat_b)
            });
        }
        SortBy::Url => {
            results.sort_by(|a, b| a.mirror.url.as_str().cmp(b.mirror.url.as_str()));
        }
    }
    results
}

/// Format test results for display
fn format_test_results(results: &[TestResult], format: OutputFormat) -> String {
    match format {
        OutputFormat::Json => {
            serde_json::to_string_pretty(results).unwrap_or_else(|_| "[]".to_string())
        }
        OutputFormat::Table | OutputFormat::Pretty => {
            if results.is_empty() {
                return "No results".to_string();
            }

            let mut output = String::new();
            output.push_str(&format!(
                "{:<50} {:<12} {:<12} {:<10} {:<10}\n",
                "URL", "Speed", "Latency", "Score", "Status"
            ));
            output.push_str(&"-".repeat(100));
            output.push('\n');

            for result in results {
                let url = truncate_string(&result.mirror.url_string(), 48);
                let speed = result.speed.map(|s| format!("{:.2} MB/s", s)).unwrap_or_else(|| "N/A".to_string());
                let latency = result.latency.map(|l| format!("{} ms", l.as_millis())).unwrap_or_else(|| "N/A".to_string());
                let score = result.score.map(|s| format!("{:.1}%", s * 100.0)).unwrap_or_else(|| "N/A".to_string());
                let status = if result.success { "" } else { "" };

                output.push_str(&format!(
                    "{:<50} {:<12} {:<12} {:<10} {:<10}\n",
                    url, speed, latency, score, status
                ));
            }

            output
        }
        OutputFormat::Compact => {
            results
                .iter()
                .map(|r| {
                    format!(
                        "{} | {} | {} | {}",
                        r.mirror.url,
                        r.mirror.format_speed(),
                        r.mirror.format_latency(),
                        r.mirror.format_score()
                    )
                })
                .collect::<Vec<_>>()
                .join("\n")
        }
    }
}

/// Format mirrors for display
fn format_mirrors(mirrors: &[Mirror], format: OutputFormat, with_tests: bool) -> String {
    match format {
        OutputFormat::Json => {
            serde_json::to_string_pretty(mirrors).unwrap_or_else(|_| "[]".to_string())
        }
        OutputFormat::Table | OutputFormat::Pretty => {
            if mirrors.is_empty() {
                return "No mirrors".to_string();
            }

            let mut output = String::new();

            if with_tests {
                output.push_str(&format!(
                    "{:<50} {:<12} {:<12} {:<10} {:<8}\n",
                    "URL", "Speed", "Latency", "Score", "Type"
                ));
            } else {
                output.push_str(&format!("{:<70} {:<8}\n", "URL", "Type"));
            }

            output.push_str(&"-".repeat(if with_tests { 100 } else { 80 }));
            output.push('\n');

            for mirror in mirrors {
                if with_tests {
                    let url = truncate_string(&mirror.url_string(), 48);
                    let mirror_type = if mirror.is_static { "Static" } else { "Dynamic" };

                    output.push_str(&format!(
                        "{:<50} {:<12} {:<12} {:<10} {:<8}\n",
                        url,
                        mirror.format_speed(),
                        mirror.format_latency(),
                        mirror.format_score(),
                        mirror_type
                    ));
                } else {
                    let url = truncate_string(&mirror.url_string(), 68);
                    let mirror_type = if mirror.is_static { "Static" } else { "Dynamic" };

                    output.push_str(&format!("{:<70} {:<8}\n", url, mirror_type));
                }
            }

            output
        }
        OutputFormat::Compact => {
            mirrors
                .iter()
                .map(|m| {
                    let type_marker = if m.is_static { "[S]" } else { "[D]" };
                    format!("{} {}", type_marker, m.url)
                })
                .collect::<Vec<_>>()
                .join("\n")
        }
    }
}

/// Format update history for display
fn format_history(history: &[UpdateRecord], format: OutputFormat) -> String {
    match format {
        OutputFormat::Json => {
            let records: Vec<_> = history
                .iter()
                .map(|h| {
                    serde_json::json!({
                        "id": h.id,
                        "mirrors_changed": h.mirrors_changed,
                        "success": h.success,
                        "error": h.error,
                        "updated_at": h.updated_at.to_rfc3339(),
                    })
                })
                .collect();

            serde_json::to_string_pretty(&records).unwrap_or_else(|_| "[]".to_string())
        }
        OutputFormat::Table | OutputFormat::Pretty => {
            if history.is_empty() {
                return "No history".to_string();
            }

            let mut output = String::new();
            output.push_str(&format!(
                "{:<5} {:<22} {:<10} {:<10} {:<30}\n",
                "ID", "Timestamp", "Mirrors", "Status", "Error"
            ));
            output.push_str(&"-".repeat(80));
            output.push('\n');

            for record in history {
                let timestamp = record.updated_at.format("%Y-%m-%d %H:%M:%S").to_string();
                let status = if record.success { "✓ Success" } else { "✗ Failed" };
                let error = record
                    .error
                    .as_ref()
                    .map(|e| truncate_string(e, 28))
                    .unwrap_or_else(|| "-".to_string());

                output.push_str(&format!(
                    "{:<5} {:<22} {:<10} {:<10} {:<30}\n",
                    record.id, timestamp, record.mirrors_changed, status, error
                ));
            }

            output
        }
        OutputFormat::Compact => {
            history
                .iter()
                .map(|h| {
                    format!(
                        "{} | {} | {} | {}",
                        h.updated_at.format("%Y-%m-%d %H:%M"),
                        h.mirrors_changed,
                        if h.success { "OK" } else { "FAIL" },
                        h.error.as_deref().unwrap_or("-")
                    )
                })
                .collect::<Vec<_>>()
                .join("\n")
        }
    }
}

/// Truncate string to specified length with ellipsis
fn truncate_string(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...", &s[..max_len.saturating_sub(3)])
    }
}