qbak 1.5.1

A single-command backup helper for Linux and POSIX systems
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
use crate::error::QbakError;
use crate::progress::ProgressConfig;
use crate::Result;
use configparser::ini::Ini;
use std::path::PathBuf;
use std::time::Duration;

#[derive(Debug, Clone)]
pub struct Config {
    pub timestamp_format: String,
    pub backup_suffix: String,
    pub preserve_permissions: bool,
    pub follow_symlinks: bool,
    pub include_hidden: bool,
    pub max_filename_length: usize,
    pub max_symlink_depth: usize,
    pub progress: ProgressConfig,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            timestamp_format: "YYYYMMDDTHHMMSS".to_string(),
            backup_suffix: "qbak".to_string(),
            preserve_permissions: true,
            follow_symlinks: true,
            include_hidden: true,
            max_filename_length: 255,
            max_symlink_depth: 32, // Reasonable default to prevent excessive traversal
            progress: ProgressConfig::auto_detect(),
        }
    }
}

/// Get default configuration
pub fn default_config() -> Config {
    Config::default()
}

/// Load configuration from file, falling back to defaults
pub fn load_config() -> Result<Config> {
    let config_path = get_config_path()?;

    if !config_path.exists() {
        return Ok(default_config());
    }

    let mut conf = Ini::new();
    conf.load(&config_path)
        .map_err(|e| QbakError::config(format!("Failed to parse config file: {e}")))?;

    let mut config = default_config();

    // Load string values
    if let Some(value) = conf.get("qbak", "timestamp_format") {
        config.timestamp_format = value;
    }
    if let Some(value) = conf.get("qbak", "backup_suffix") {
        config.backup_suffix = value;
    }

    // Load boolean values
    if let Some(value) = conf.get("qbak", "preserve_permissions") {
        config.preserve_permissions = parse_bool(&value).unwrap_or(config.preserve_permissions);
    }
    if let Some(value) = conf.get("qbak", "follow_symlinks") {
        config.follow_symlinks = parse_bool(&value).unwrap_or(config.follow_symlinks);
    }
    if let Some(value) = conf.get("qbak", "include_hidden") {
        config.include_hidden = parse_bool(&value).unwrap_or(config.include_hidden);
    }

    // Load numeric values
    if let Some(value) = conf.get("qbak", "max_filename_length") {
        config.max_filename_length = value
            .parse()
            .map_err(|_| QbakError::config(format!("Invalid max_filename_length: {value}")))?;
    }
    if let Some(value) = conf.get("qbak", "max_symlink_depth") {
        config.max_symlink_depth = value
            .parse()
            .map_err(|_| QbakError::config(format!("Invalid max_symlink_depth: {value}")))?;
    }

    // Load progress configuration
    if let Some(value) = conf.get("progress", "enabled") {
        config.progress.enabled = parse_bool(&value).unwrap_or(config.progress.enabled);
    }
    if let Some(value) = conf.get("progress", "force_enabled") {
        config.progress.force_enabled = parse_bool(&value).unwrap_or(config.progress.force_enabled);
    }
    if let Some(value) = conf.get("progress", "min_files") {
        config.progress.min_files_threshold = value
            .parse()
            .map_err(|_| QbakError::config(format!("Invalid min_files: {value}")))?;
    }
    if let Some(value) = conf.get("progress", "min_size_mb") {
        let mb: u64 = value
            .parse()
            .map_err(|_| QbakError::config(format!("Invalid min_size_mb: {value}")))?;
        config.progress.min_size_threshold = mb * 1024 * 1024;
    }
    if let Some(value) = conf.get("progress", "min_duration_seconds") {
        let seconds: u64 = value
            .parse()
            .map_err(|_| QbakError::config(format!("Invalid min_duration_seconds: {value}")))?;
        config.progress.min_duration_threshold = Duration::from_secs(seconds);
    }

    Ok(config)
}

/// Get the configuration file path for the current platform
fn get_config_path() -> Result<PathBuf> {
    #[cfg(target_os = "windows")]
    {
        if let Some(appdata) = std::env::var_os("APPDATA") {
            return Ok(PathBuf::from(appdata).join("qbak").join("config.ini"));
        }
    }

    // Unix-like systems (Linux, macOS, etc.)
    if let Some(config_dir) = std::env::var_os("XDG_CONFIG_HOME") {
        Ok(PathBuf::from(config_dir).join("qbak").join("config.ini"))
    } else if let Some(home) = std::env::var_os("HOME") {
        Ok(PathBuf::from(home)
            .join(".config")
            .join("qbak")
            .join("config.ini"))
    } else {
        Err(QbakError::config("Could not determine config directory"))
    }
}

/// Parse a boolean value from INI string
fn parse_bool(value: &str) -> Option<bool> {
    match value.to_lowercase().as_str() {
        "true" | "yes" | "1" | "on" => Some(true),
        "false" | "no" | "0" | "off" => Some(false),
        _ => None,
    }
}

/// Create a sample configuration file
pub fn create_sample_config() -> String {
    r#"[qbak]
# Timestamp format for backup names (ISO-8601 basic format)
timestamp_format = YYYYMMDDTHHMMSS

# Suffix added to backup filenames  
backup_suffix = qbak

# Preserve original file permissions and timestamps (true/false)
preserve_permissions = true

# Follow symbolic links (copy target) or preserve as symlinks
follow_symlinks = true

# Include hidden files when backing up directories  
include_hidden = true

# Maximum filename length before showing error
max_filename_length = 255

# Maximum symlink depth to follow (security feature)
max_symlink_depth = 32

[progress]
# Enable/disable progress indication (can be overridden by command line flags)
enabled = true

# Force progress indication regardless of thresholds (equivalent to always using --progress)
force_enabled = false

# Minimum thresholds for showing progress (ignored if --progress flag is used)
min_files = 50
min_size_mb = 10
min_duration_seconds = 2
"#
    .to_string()
}

/// Display the current configuration in a user-friendly format
pub fn dump_config(config: &Config) -> Result<()> {
    let config_path = get_config_path()?;

    println!("qbak Configuration");
    println!("==================");
    println!();

    // Show config file path and status
    if config_path.exists() {
        let path_display = config_path.display();
        println!("Config file: {path_display} (found)");
    } else {
        println!(
            "Config file: {} (not found, using defaults)",
            config_path.display()
        );
    }
    println!();

    // Show current settings
    println!("Current Settings:");
    println!("----------------");
    let timestamp_format = &config.timestamp_format;
    let backup_suffix = &config.backup_suffix;
    let preserve_permissions = config.preserve_permissions;
    let follow_symlinks = config.follow_symlinks;
    let include_hidden = config.include_hidden;
    let max_filename_length = config.max_filename_length;
    println!("timestamp_format     = {timestamp_format}");
    println!("backup_suffix        = {backup_suffix}");
    println!("preserve_permissions = {preserve_permissions}");
    println!("follow_symlinks      = {follow_symlinks}");
    println!("include_hidden       = {include_hidden}");
    println!("max_filename_length  = {max_filename_length}");
    println!();

    // Show progress settings
    println!("Progress Settings:");
    println!("-----------------");
    let progress = &config.progress;
    println!("enabled              = {}", progress.enabled);
    println!("force_enabled        = {}", progress.force_enabled);
    println!("min_files_threshold  = {}", progress.min_files_threshold);
    println!(
        "min_size_threshold   = {} MB",
        progress.min_size_threshold / (1024 * 1024)
    );
    println!(
        "min_duration_threshold = {} seconds",
        progress.min_duration_threshold.as_secs()
    );
    println!("supports_ansi        = {}", progress.supports_ansi);
    println!("terminal_width       = {}", progress.terminal_width);
    println!("is_interactive       = {}", progress.is_interactive);
    println!();

    // Show example usage
    println!("Example backup names with current settings:");
    println!("------------------------------------------");
    println!(
        "example.txt → example-YYYYMMDDTHHMMSS-{}.txt",
        config.backup_suffix
    );
    println!(
        "data.tar.gz → data.tar-YYYYMMDDTHHMMSS-{}.gz",
        config.backup_suffix
    );
    let suffix = &config.backup_suffix;
    println!("no-ext → no-ext-YYYYMMDDTHHMMSS-{suffix}");
    println!();

    if !config_path.exists() {
        println!("To create a configuration file:");
        println!("------------------------------");
        println!(
            "1. Create directory: mkdir -p {}",
            config_path.parent().unwrap().display()
        );
        println!("2. Create config file with your preferred settings");
        println!("3. Use 'qbak --dump-config' again to verify");
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::sync::Mutex;
    use tempfile::tempdir;

    // Mutex to serialize tests that modify environment variables
    static ENV_MUTEX: Mutex<()> = Mutex::new(());

    #[test]
    fn test_default_config() {
        let config = default_config();
        assert_eq!(config.timestamp_format, "YYYYMMDDTHHMMSS");
        assert_eq!(config.backup_suffix, "qbak");
        assert!(config.preserve_permissions);
        assert!(config.follow_symlinks);
        assert!(config.include_hidden);
        assert_eq!(config.max_filename_length, 255);
    }

    #[test]
    fn test_parse_bool() {
        assert_eq!(parse_bool("true"), Some(true));
        assert_eq!(parse_bool("false"), Some(false));
        assert_eq!(parse_bool("yes"), Some(true));
        assert_eq!(parse_bool("no"), Some(false));
        assert_eq!(parse_bool("1"), Some(true));
        assert_eq!(parse_bool("0"), Some(false));
        assert_eq!(parse_bool("on"), Some(true));
        assert_eq!(parse_bool("off"), Some(false));
        assert_eq!(parse_bool("TRUE"), Some(true));
        assert_eq!(parse_bool("FALSE"), Some(false));
        assert_eq!(parse_bool("invalid"), None);
        assert_eq!(parse_bool(""), None);
        assert_eq!(parse_bool("maybe"), None);
    }

    #[test]
    fn test_load_config_nonexistent_file() {
        let _guard = ENV_MUTEX.lock().unwrap(); // Serialize environment access

        // Save original environment
        #[cfg(not(target_os = "windows"))]
        let (original_xdg, original_home) = (
            std::env::var_os("XDG_CONFIG_HOME"),
            std::env::var_os("HOME"),
        );
        #[cfg(target_os = "windows")]
        let original_appdata = std::env::var_os("APPDATA");

        // Set a temp directory so config loading succeeds but file doesn't exist
        let dir = tempdir().unwrap();

        #[cfg(not(target_os = "windows"))]
        std::env::set_var("XDG_CONFIG_HOME", dir.path());
        #[cfg(target_os = "windows")]
        std::env::set_var("APPDATA", dir.path());

        // Test loading config when file doesn't exist - should return defaults
        let config = load_config().unwrap();
        let default = default_config();

        assert_eq!(config.timestamp_format, default.timestamp_format);
        assert_eq!(config.backup_suffix, default.backup_suffix);
        assert_eq!(config.preserve_permissions, default.preserve_permissions);

        // Restore original environment
        #[cfg(not(target_os = "windows"))]
        {
            if let Some(xdg) = original_xdg {
                std::env::set_var("XDG_CONFIG_HOME", xdg);
            } else {
                std::env::remove_var("XDG_CONFIG_HOME");
            }
            if let Some(home) = original_home {
                std::env::set_var("HOME", home);
            } else {
                std::env::remove_var("HOME");
            }
        }
        #[cfg(target_os = "windows")]
        {
            if let Some(appdata) = original_appdata {
                std::env::set_var("APPDATA", appdata);
            } else {
                std::env::remove_var("APPDATA");
            }
        }
    }

    #[test]
    fn test_config_from_file() {
        let _guard = ENV_MUTEX.lock().unwrap(); // Serialize environment access

        // Save original environment
        #[cfg(not(target_os = "windows"))]
        let (original_xdg, original_home) = (
            std::env::var_os("XDG_CONFIG_HOME"),
            std::env::var_os("HOME"),
        );
        #[cfg(target_os = "windows")]
        let original_appdata = std::env::var_os("APPDATA");

        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("qbak");
        fs::create_dir_all(&config_dir).unwrap();
        let config_path = config_dir.join("config.ini");

        // Create a test config file
        let config_content = r#"[qbak]
timestamp_format = TEST_FORMAT
backup_suffix = test-suffix
preserve_permissions = false
follow_symlinks = false
include_hidden = false
max_filename_length = 100
"#;
        fs::write(&config_path, config_content).unwrap();

        // Clear and set environment variables for clean test environment
        #[cfg(not(target_os = "windows"))]
        {
            std::env::remove_var("HOME"); // Clear HOME to ensure XDG_CONFIG_HOME is used
            std::env::set_var("XDG_CONFIG_HOME", dir.path());
        }
        #[cfg(target_os = "windows")]
        std::env::set_var("APPDATA", dir.path());

        let config = load_config().unwrap();

        assert_eq!(config.timestamp_format, "TEST_FORMAT");
        assert_eq!(config.backup_suffix, "test-suffix");
        assert!(!config.preserve_permissions);
        assert!(!config.follow_symlinks);
        assert!(!config.include_hidden);
        assert_eq!(config.max_filename_length, 100);

        // Restore original environment
        #[cfg(not(target_os = "windows"))]
        {
            if let Some(xdg) = original_xdg {
                std::env::set_var("XDG_CONFIG_HOME", xdg);
            } else {
                std::env::remove_var("XDG_CONFIG_HOME");
            }
            if let Some(home) = original_home {
                std::env::set_var("HOME", home);
            } else {
                std::env::remove_var("HOME");
            }
        }
        #[cfg(target_os = "windows")]
        {
            if let Some(appdata) = original_appdata {
                std::env::set_var("APPDATA", appdata);
            } else {
                std::env::remove_var("APPDATA");
            }
        }
    }

    #[test]
    fn test_config_partial_override() {
        let _guard = ENV_MUTEX.lock().unwrap(); // Serialize environment access

        // Save original environment
        #[cfg(not(target_os = "windows"))]
        let (original_xdg, original_home) = (
            std::env::var_os("XDG_CONFIG_HOME"),
            std::env::var_os("HOME"),
        );
        #[cfg(target_os = "windows")]
        let original_appdata = std::env::var_os("APPDATA");

        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("qbak");
        fs::create_dir_all(&config_dir).unwrap();
        let config_path = config_dir.join("config.ini");

        // Create a config file with only some values
        let config_content = r#"[qbak]
backup_suffix = custom
"#;
        fs::write(&config_path, config_content).unwrap();

        // Clear and set environment variables for clean test environment
        #[cfg(not(target_os = "windows"))]
        {
            std::env::remove_var("HOME"); // Clear HOME to ensure XDG_CONFIG_HOME is used
            std::env::set_var("XDG_CONFIG_HOME", dir.path());
        }
        #[cfg(target_os = "windows")]
        std::env::set_var("APPDATA", dir.path());

        let config = load_config().unwrap();
        let default = default_config();

        // Overridden values
        assert_eq!(config.backup_suffix, "custom");

        // Default values should remain
        assert_eq!(config.timestamp_format, default.timestamp_format);
        assert_eq!(config.preserve_permissions, default.preserve_permissions);
        assert_eq!(config.follow_symlinks, default.follow_symlinks);
        assert_eq!(config.include_hidden, default.include_hidden);
        assert_eq!(config.max_filename_length, default.max_filename_length);

        // Restore original environment
        #[cfg(not(target_os = "windows"))]
        {
            if let Some(xdg) = original_xdg {
                std::env::set_var("XDG_CONFIG_HOME", xdg);
            } else {
                std::env::remove_var("XDG_CONFIG_HOME");
            }
            if let Some(home) = original_home {
                std::env::set_var("HOME", home);
            } else {
                std::env::remove_var("HOME");
            }
        }
        #[cfg(target_os = "windows")]
        {
            if let Some(appdata) = original_appdata {
                std::env::set_var("APPDATA", appdata);
            } else {
                std::env::remove_var("APPDATA");
            }
        }
    }

    #[test]
    fn test_config_invalid_boolean() {
        let _guard = ENV_MUTEX.lock().unwrap(); // Serialize environment access

        // Save original environment
        #[cfg(not(target_os = "windows"))]
        let (original_xdg, original_home) = (
            std::env::var_os("XDG_CONFIG_HOME"),
            std::env::var_os("HOME"),
        );
        #[cfg(target_os = "windows")]
        let original_appdata = std::env::var_os("APPDATA");

        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("qbak");
        fs::create_dir_all(&config_dir).unwrap();
        let config_path = config_dir.join("config.ini");

        let config_content = r#"[qbak]
preserve_permissions = maybe
follow_symlinks = invalid
include_hidden = not_a_boolean
"#;
        fs::write(&config_path, config_content).unwrap();

        // Clear and set environment variables for clean test environment
        #[cfg(not(target_os = "windows"))]
        {
            std::env::remove_var("HOME"); // Clear HOME to ensure XDG_CONFIG_HOME is used
            std::env::set_var("XDG_CONFIG_HOME", dir.path());
        }
        #[cfg(target_os = "windows")]
        std::env::set_var("APPDATA", dir.path());

        let config = load_config().unwrap();
        let default = default_config();

        // Invalid booleans should fallback to defaults
        assert_eq!(config.preserve_permissions, default.preserve_permissions);
        assert_eq!(config.follow_symlinks, default.follow_symlinks);

        // Restore original environment
        #[cfg(not(target_os = "windows"))]
        {
            if let Some(xdg) = original_xdg {
                std::env::set_var("XDG_CONFIG_HOME", xdg);
            } else {
                std::env::remove_var("XDG_CONFIG_HOME");
            }
            if let Some(home) = original_home {
                std::env::set_var("HOME", home);
            } else {
                std::env::remove_var("HOME");
            }
        }
        #[cfg(target_os = "windows")]
        {
            if let Some(appdata) = original_appdata {
                std::env::set_var("APPDATA", appdata);
            } else {
                std::env::remove_var("APPDATA");
            }
        }
    }

    #[test]
    fn test_config_invalid_numeric() {
        let _guard = ENV_MUTEX.lock().unwrap(); // Serialize environment access

        // Save original environment
        #[cfg(not(target_os = "windows"))]
        let (original_xdg, original_home) = (
            std::env::var_os("XDG_CONFIG_HOME"),
            std::env::var_os("HOME"),
        );
        #[cfg(target_os = "windows")]
        let original_appdata = std::env::var_os("APPDATA");

        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("qbak");
        fs::create_dir_all(&config_dir).unwrap();
        let config_path = config_dir.join("config.ini");

        let config_content = r#"[qbak]
max_filename_length = not_a_number
"#;
        fs::write(&config_path, config_content).unwrap();

        // Clear and set environment variables for clean test environment
        #[cfg(not(target_os = "windows"))]
        {
            std::env::remove_var("HOME"); // Clear HOME to ensure XDG_CONFIG_HOME is used
            std::env::set_var("XDG_CONFIG_HOME", dir.path());
        }
        #[cfg(target_os = "windows")]
        std::env::set_var("APPDATA", dir.path());

        let result = load_config();
        assert!(result.is_err()); // Should fail to parse invalid numbers

        // Restore original environment
        #[cfg(not(target_os = "windows"))]
        {
            if let Some(xdg) = original_xdg {
                std::env::set_var("XDG_CONFIG_HOME", xdg);
            } else {
                std::env::remove_var("XDG_CONFIG_HOME");
            }
            if let Some(home) = original_home {
                std::env::set_var("HOME", home);
            } else {
                std::env::remove_var("HOME");
            }
        }
        #[cfg(target_os = "windows")]
        {
            if let Some(appdata) = original_appdata {
                std::env::set_var("APPDATA", appdata);
            } else {
                std::env::remove_var("APPDATA");
            }
        }
    }

    #[test]
    fn test_config_malformed_file() {
        let _guard = ENV_MUTEX.lock().unwrap(); // Serialize environment access

        // Save original environment
        #[cfg(not(target_os = "windows"))]
        let (original_xdg, original_home) = (
            std::env::var_os("XDG_CONFIG_HOME"),
            std::env::var_os("HOME"),
        );
        #[cfg(target_os = "windows")]
        let original_appdata = std::env::var_os("APPDATA");

        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("qbak");
        fs::create_dir_all(&config_dir).unwrap();
        let config_path = config_dir.join("config.ini");

        // Create binary/invalid content that should definitely fail
        let config_content = vec![0u8, 159u8, 146u8, 150u8]; // Invalid UTF-8 bytes
        fs::write(&config_path, config_content).unwrap();

        // Clear and set environment variables for clean test environment
        #[cfg(not(target_os = "windows"))]
        {
            std::env::remove_var("HOME"); // Clear HOME to ensure XDG_CONFIG_HOME is used
            std::env::set_var("XDG_CONFIG_HOME", dir.path());
        }
        #[cfg(target_os = "windows")]
        std::env::set_var("APPDATA", dir.path());

        let result = load_config();
        // The configparser is quite tolerant, but invalid UTF-8 should fail
        // If it doesn't fail, that's actually fine - just means robust parsing
        match result {
            Err(_) => {
                // Good - caught the malformed file
            }
            Ok(config) => {
                // Parser is very robust - that's actually fine for a backup tool
                // Just verify it returns default values when it can't parse sections
                let default = default_config();
                assert_eq!(config.timestamp_format, default.timestamp_format);
            }
        }

        // Restore original environment
        #[cfg(not(target_os = "windows"))]
        {
            if let Some(xdg) = original_xdg {
                std::env::set_var("XDG_CONFIG_HOME", xdg);
            } else {
                std::env::remove_var("XDG_CONFIG_HOME");
            }
            if let Some(home) = original_home {
                std::env::set_var("HOME", home);
            } else {
                std::env::remove_var("HOME");
            }
        }
        #[cfg(target_os = "windows")]
        {
            if let Some(appdata) = original_appdata {
                std::env::set_var("APPDATA", appdata);
            } else {
                std::env::remove_var("APPDATA");
            }
        }
    }

    #[test]
    fn test_create_sample_config() {
        let sample = create_sample_config();

        assert!(sample.contains("[qbak]"));
        assert!(sample.contains("timestamp_format"));
        assert!(sample.contains("backup_suffix"));
        assert!(sample.contains("preserve_permissions"));
        assert!(sample.contains("follow_symlinks"));
        assert!(sample.contains("include_hidden"));
        assert!(sample.contains("max_filename_length"));
        assert!(sample.contains("max_symlink_depth"));
        println!("{sample}");

        // Verify it's valid INI by parsing it
        let dir = tempdir().unwrap();
        let config_path = dir.path().join("sample.ini");
        fs::write(&config_path, &sample).unwrap();

        let mut conf = Ini::new();
        assert!(conf.load(&config_path).is_ok());
    }

    #[test]
    fn test_config_with_empty_section() {
        let _guard = ENV_MUTEX.lock().unwrap(); // Serialize environment access

        // Save original environment
        #[cfg(not(target_os = "windows"))]
        let (original_xdg, original_home) = (
            std::env::var_os("XDG_CONFIG_HOME"),
            std::env::var_os("HOME"),
        );
        #[cfg(target_os = "windows")]
        let original_appdata = std::env::var_os("APPDATA");

        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("qbak");
        fs::create_dir_all(&config_dir).unwrap();
        let config_path = config_dir.join("config.ini");

        // Config file with empty qbak section
        let config_content = r#"[qbak]
[other_section]
some_key = some_value
"#;
        fs::write(&config_path, config_content).unwrap();

        // Clear and set environment variables for clean test environment
        #[cfg(not(target_os = "windows"))]
        {
            std::env::remove_var("HOME"); // Clear HOME to ensure XDG_CONFIG_HOME is used
            std::env::set_var("XDG_CONFIG_HOME", dir.path());
        }
        #[cfg(target_os = "windows")]
        std::env::set_var("APPDATA", dir.path());

        let config = load_config().unwrap();
        let default = default_config();

        // Should use all default values
        assert_eq!(config.timestamp_format, default.timestamp_format);
        assert_eq!(config.backup_suffix, default.backup_suffix);
        assert_eq!(config.preserve_permissions, default.preserve_permissions);
        assert_eq!(config.follow_symlinks, default.follow_symlinks);
        assert_eq!(config.include_hidden, default.include_hidden);
        assert_eq!(config.max_filename_length, default.max_filename_length);

        // Restore original environment
        #[cfg(not(target_os = "windows"))]
        {
            if let Some(xdg) = original_xdg {
                std::env::set_var("XDG_CONFIG_HOME", xdg);
            } else {
                std::env::remove_var("XDG_CONFIG_HOME");
            }
            if let Some(home) = original_home {
                std::env::set_var("HOME", home);
            } else {
                std::env::remove_var("HOME");
            }
        }
        #[cfg(target_os = "windows")]
        {
            if let Some(appdata) = original_appdata {
                std::env::set_var("APPDATA", appdata);
            } else {
                std::env::remove_var("APPDATA");
            }
        }
    }

    #[test]
    fn test_get_config_path_xdg() {
        let _guard = ENV_MUTEX.lock().unwrap(); // Serialize environment access

        #[cfg(not(target_os = "windows"))]
        {
            // Save original environment
            let original_xdg = std::env::var_os("XDG_CONFIG_HOME");

            let dir = tempdir().unwrap();
            std::env::set_var("XDG_CONFIG_HOME", dir.path());

            let config_path = get_config_path().unwrap();
            let expected = dir.path().join("qbak").join("config.ini");

            assert_eq!(config_path, expected);

            // Restore original environment
            if let Some(xdg) = original_xdg {
                std::env::set_var("XDG_CONFIG_HOME", xdg);
            } else {
                std::env::remove_var("XDG_CONFIG_HOME");
            }
        }

        // On Windows, test APPDATA path
        #[cfg(target_os = "windows")]
        {
            // Save original environment
            let original_appdata = std::env::var_os("APPDATA");

            let dir = tempdir().unwrap();
            std::env::set_var("APPDATA", dir.path());

            let config_path = get_config_path().unwrap();
            let expected = dir.path().join("qbak").join("config.ini");

            assert_eq!(config_path, expected);

            // Restore original environment
            if let Some(appdata) = original_appdata {
                std::env::set_var("APPDATA", appdata);
            } else {
                std::env::remove_var("APPDATA");
            }
        }
    }

    #[test]
    fn test_get_config_path_home() {
        let _guard = ENV_MUTEX.lock().unwrap(); // Serialize environment access

        #[cfg(not(target_os = "windows"))]
        {
            // Save original environment
            let original_xdg = std::env::var_os("XDG_CONFIG_HOME");
            let original_home = std::env::var_os("HOME");

            // Remove XDG_CONFIG_HOME to test HOME fallback
            std::env::remove_var("XDG_CONFIG_HOME");

            // Ensure HOME is available for this test
            if let Some(home) = original_home.clone() {
                std::env::set_var("HOME", &home);

                let config_path = get_config_path().unwrap();
                let expected = PathBuf::from(home)
                    .join(".config")
                    .join("qbak")
                    .join("config.ini");

                assert_eq!(config_path, expected);
            }

            // Restore original environment
            if let Some(xdg) = original_xdg {
                std::env::set_var("XDG_CONFIG_HOME", xdg);
            } else {
                std::env::remove_var("XDG_CONFIG_HOME");
            }
            if let Some(home) = original_home {
                std::env::set_var("HOME", home);
            } else {
                std::env::remove_var("HOME");
            }
        }
    }

    #[test]
    fn test_dump_config() {
        let config = default_config();
        let result = dump_config(&config);
        // Should not fail - actual output verification would require capturing stdout
        assert!(result.is_ok());
    }

    #[test]
    fn test_get_config_path_no_env() {
        let _guard = ENV_MUTEX.lock().unwrap(); // Serialize environment access

        #[cfg(not(target_os = "windows"))]
        {
            // Save original environment
            let original_xdg = std::env::var_os("XDG_CONFIG_HOME");
            let original_home = std::env::var_os("HOME");

            // Remove both environment variables
            std::env::remove_var("XDG_CONFIG_HOME");
            std::env::remove_var("HOME");

            let result = get_config_path();
            assert!(result.is_err()); // Should fail when no env vars are set

            // Restore original environment immediately
            if let Some(xdg) = original_xdg {
                std::env::set_var("XDG_CONFIG_HOME", xdg);
            } else {
                std::env::remove_var("XDG_CONFIG_HOME");
            }
            if let Some(home) = original_home {
                std::env::set_var("HOME", home);
            } else {
                std::env::remove_var("HOME");
            }
        }

        #[cfg(target_os = "windows")]
        {
            // Save original environment
            let original_appdata = std::env::var_os("APPDATA");

            // Remove APPDATA environment variable
            std::env::remove_var("APPDATA");

            let result = get_config_path();
            assert!(result.is_err()); // Should fail when APPDATA is not set

            // Restore original environment immediately
            if let Some(appdata) = original_appdata {
                std::env::set_var("APPDATA", appdata);
            } else {
                std::env::remove_var("APPDATA");
            }
        }
    }
}