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
//! Backup and restore functionality for mirror configurations
//!
//! This module provides comprehensive backup management including creation,
//! restoration, rotation, and diffing of backup files.

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use tracing::{debug, info, warn};

/// Backup metadata stored alongside backup files
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackupMetadata {
    /// Timestamp when backup was created
    pub created_at: DateTime<Utc>,
    /// Number of files included in the backup
    pub file_count: usize,
    /// Total size of backed up files in bytes
    pub total_size: u64,
    /// Map of original file paths to their backup locations
    pub files: HashMap<PathBuf, BackupFileInfo>,
    /// Optional description or reason for the backup
    pub description: Option<String>,
    /// Version of SMirrors that created the backup
    pub version: String,
}

/// Information about a backed up file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackupFileInfo {
    /// Original file path
    pub original_path: PathBuf,
    /// Backup file path (relative to backup directory)
    pub backup_path: PathBuf,
    /// File size in bytes
    pub size: u64,
    /// File modification time
    pub modified_at: DateTime<Utc>,
    /// SHA256 checksum of the file
    pub checksum: Option<String>,
}

/// Backup manager for handling configuration file backups
pub struct BackupManager {
    backup_dir: PathBuf,
    max_backups: usize,
}

/// Backup listing entry
#[derive(Debug, Clone)]
pub struct BackupEntry {
    pub id: String,
    pub created_at: DateTime<Utc>,
    pub file_count: usize,
    pub total_size: u64,
    pub description: Option<String>,
    pub path: PathBuf,
}

/// Difference between two backups
#[derive(Debug, Clone)]
pub struct BackupDiff {
    pub added_files: Vec<PathBuf>,
    pub removed_files: Vec<PathBuf>,
    pub modified_files: Vec<PathBuf>,
}

impl BackupManager {
    /// Create a new backup manager
    ///
    /// # Arguments
    /// * `backup_dir` - Directory to store backups
    /// * `max_backups` - Maximum number of backups to retain (older ones are deleted)
    pub fn new<P: AsRef<Path>>(backup_dir: P, max_backups: usize) -> Result<Self> {
        let backup_dir = backup_dir.as_ref().to_path_buf();

        // Create backup directory if it doesn't exist
        if !backup_dir.exists() {
            fs::create_dir_all(&backup_dir)
                .with_context(|| format!("Failed to create backup directory: {:?}", backup_dir))?;
            info!("Created backup directory: {:?}", backup_dir);
        }

        Ok(Self {
            backup_dir,
            max_backups,
        })
    }

    /// Create a backup of specified files
    ///
    /// # Arguments
    /// * `files` - Paths to files that should be backed up
    /// * `description` - Optional description for the backup
    ///
    /// # Returns
    /// Backup ID (timestamp-based identifier)
    pub fn create_backup(
        &self,
        files: &[PathBuf],
        description: Option<String>,
    ) -> Result<String> {
        let backup_id = Self::generate_backup_id();
        let backup_path = self.backup_dir.join(&backup_id);

        info!("Creating backup with ID: {}", backup_id);

        // Create backup subdirectory
        fs::create_dir_all(&backup_path)
            .with_context(|| format!("Failed to create backup directory: {:?}", backup_path))?;

        let mut metadata = BackupMetadata {
            created_at: Utc::now(),
            file_count: 0,
            total_size: 0,
            files: HashMap::new(),
            description,
            version: crate::VERSION.to_string(),
        };

        // Copy each file to the backup directory
        for original_file in files {
            if !original_file.exists() {
                warn!("Skipping non-existent file: {:?}", original_file);
                continue;
            }

            if !original_file.is_file() {
                warn!("Skipping non-file path: {:?}", original_file);
                continue;
            }

            // Create relative backup path preserving directory structure
            let backup_file_path = self.create_backup_file_path(&backup_path, original_file)?;

            // Copy file
            self.copy_file_with_metadata(original_file, &backup_file_path)?;

            // Get file metadata
            let file_metadata = fs::metadata(original_file)
                .with_context(|| format!("Failed to read metadata for: {:?}", original_file))?;

            let size = file_metadata.len();
            let modified_at = file_metadata.modified()
                .ok()
                .and_then(|t| DateTime::from_timestamp(
                    t.duration_since(std::time::UNIX_EPOCH).ok()?.as_secs() as i64,
                    0
                ))
                .unwrap_or_else(Utc::now);

            // Calculate checksum
            let checksum = self.calculate_checksum(original_file).ok();

            // Determine relative path for storage
            let relative_backup_path = backup_file_path
                .strip_prefix(&backup_path)
                .unwrap_or(&backup_file_path)
                .to_path_buf();

            let file_info = BackupFileInfo {
                original_path: original_file.clone(),
                backup_path: relative_backup_path,
                size,
                modified_at,
                checksum,
            };

            metadata.files.insert(original_file.clone(), file_info);
            metadata.file_count += 1;
            metadata.total_size += size;

            debug!("Backed up file: {:?} ({} bytes)", original_file, size);
        }

        // Save metadata
        self.save_metadata(&backup_path, &metadata)?;

        info!(
            "Backup created: {} files, {} bytes total",
            metadata.file_count, metadata.total_size
        );

        // Rotate old backups
        self.rotate_backups()?;

        Ok(backup_id)
    }

    /// Restore files from a backup
    ///
    /// # Arguments
    /// * `backup_id` - ID of the backup to restore
    /// * `validate` - Whether to validate checksums before restoring
    ///
    /// # Returns
    /// Number of files restored
    pub fn restore_backup(&self, backup_id: &str, validate: bool) -> Result<usize> {
        let backup_path = self.backup_dir.join(backup_id);

        if !backup_path.exists() {
            anyhow::bail!("Backup not found: {}", backup_id);
        }

        info!("Restoring backup: {}", backup_id);

        let metadata = self.load_metadata(&backup_path)?;

        if validate {
            self.validate_backup(&backup_path, &metadata)?;
        }

        let mut restored_count = 0;

        for (original_path, file_info) in &metadata.files {
            let backup_file = backup_path.join(&file_info.backup_path);

            if !backup_file.exists() {
                warn!("Backup file not found: {:?}, skipping", backup_file);
                continue;
            }

            // Create parent directory if needed
            if let Some(parent) = original_path.parent() {
                fs::create_dir_all(parent).with_context(|| {
                    format!("Failed to create parent directory: {:?}", parent)
                })?;
            }

            // Copy file back to original location
            fs::copy(&backup_file, original_path).with_context(|| {
                format!("Failed to restore file from {:?} to {:?}", backup_file, original_path)
            })?;

            restored_count += 1;
            debug!("Restored file: {:?}", original_path);
        }

        info!("Restored {} files from backup", restored_count);

        Ok(restored_count)
    }

    /// List all available backups
    ///
    /// # Returns
    /// Vector of backup entries, sorted by creation time (newest first)
    pub fn list_backups(&self) -> Result<Vec<BackupEntry>> {
        let mut entries = Vec::new();

        if !self.backup_dir.exists() {
            return Ok(entries);
        }

        let dir_entries = fs::read_dir(&self.backup_dir)
            .with_context(|| format!("Failed to read backup directory: {:?}", self.backup_dir))?;

        for entry in dir_entries {
            let entry = entry.context("Failed to read directory entry")?;
            let path = entry.path();

            if !path.is_dir() {
                continue;
            }

            let backup_id = path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("")
                .to_string();

            // Try to load metadata
            match self.load_metadata(&path) {
                Ok(metadata) => {
                    entries.push(BackupEntry {
                        id: backup_id,
                        created_at: metadata.created_at,
                        file_count: metadata.file_count,
                        total_size: metadata.total_size,
                        description: metadata.description,
                        path,
                    });
                }
                Err(e) => {
                    warn!("Failed to load metadata for backup {}: {}", backup_id, e);
                }
            }
        }

        // Sort by creation time, newest first
        entries.sort_by(|a, b| b.created_at.cmp(&a.created_at));

        Ok(entries)
    }

    /// Calculate difference between two backups
    ///
    /// # Arguments
    /// * `backup_id1` - ID of the first backup (older)
    /// * `backup_id2` - ID of the second backup (newer)
    ///
    /// # Returns
    /// Difference showing added, removed, and modified files
    pub fn diff_backups(&self, backup_id1: &str, backup_id2: &str) -> Result<BackupDiff> {
        let backup1_path = self.backup_dir.join(backup_id1);
        let backup2_path = self.backup_dir.join(backup_id2);

        let metadata1 = self.load_metadata(&backup1_path)?;
        let metadata2 = self.load_metadata(&backup2_path)?;

        let mut added_files = Vec::new();
        let mut removed_files = Vec::new();
        let mut modified_files = Vec::new();

        // Find added and modified files
        for (path, info2) in &metadata2.files {
            match metadata1.files.get(path) {
                Some(info1) => {
                    // File exists in both backups, check if modified
                    if self.files_differ(info1, info2) {
                        modified_files.push(path.clone());
                    }
                }
                None => {
                    // File only exists in newer backup
                    added_files.push(path.clone());
                }
            }
        }

        // Find removed files
        for path in metadata1.files.keys() {
            if !metadata2.files.contains_key(path) {
                removed_files.push(path.clone());
            }
        }

        Ok(BackupDiff {
            added_files,
            removed_files,
            modified_files,
        })
    }

    /// Delete a specific backup
    ///
    /// # Arguments
    /// * `backup_id` - ID of the backup to delete
    pub fn delete_backup(&self, backup_id: &str) -> Result<()> {
        let backup_path = self.backup_dir.join(backup_id);

        if !backup_path.exists() {
            anyhow::bail!("Backup not found: {}", backup_id);
        }

        fs::remove_dir_all(&backup_path)
            .with_context(|| format!("Failed to delete backup: {:?}", backup_path))?;

        info!("Deleted backup: {}", backup_id);

        Ok(())
    }

    /// Get the most recent backup ID
    pub fn get_latest_backup_id(&self) -> Result<Option<String>> {
        let backups = self.list_backups()?;

        Ok(backups.first().map(|e| e.id.clone()))
    }

    /// Rotate backups, keeping only the N most recent ones
    fn rotate_backups(&self) -> Result<()> {
        let mut backups = self.list_backups()?;

        if backups.len() <= self.max_backups {
            return Ok(());
        }

        // Sort by creation time, oldest first
        backups.sort_by(|a, b| a.created_at.cmp(&b.created_at));

        let to_delete = backups.len() - self.max_backups;

        for backup in backups.iter().take(to_delete) {
            info!("Rotating out old backup: {}", backup.id);
            self.delete_backup(&backup.id)?;
        }

        Ok(())
    }

    /// Generate a unique backup ID based on timestamp
    fn generate_backup_id() -> String {
        let now = Utc::now();
        now.format("%Y%m%d_%H%M%S_%3f").to_string()
    }

    /// Create a backup file path preserving directory structure
    fn create_backup_file_path(
        &self,
        backup_dir: &Path,
        original_file: &Path,
    ) -> Result<PathBuf> {
        // Get absolute path
        let absolute = original_file.canonicalize().unwrap_or_else(|_| original_file.to_path_buf());

        // Create a safe path within backup directory
        // Replace path separators with underscores for root components
        let components: Vec<_> = absolute.components().collect();
        let mut safe_path = backup_dir.to_path_buf();

        for (i, component) in components.iter().enumerate() {
            let component_str = component.as_os_str().to_string_lossy();

            // For the first few components, sanitize them
            if i < 2 {
                let sanitized = component_str.replace('/', "_").replace('\\', "_");
                safe_path.push(sanitized);
            } else {
                safe_path.push(component_str.as_ref());
            }
        }

        // Create parent directories
        if let Some(parent) = safe_path.parent() {
            fs::create_dir_all(parent)
                .with_context(|| format!("Failed to create backup subdirectory: {:?}", parent))?;
        }

        Ok(safe_path)
    }

    /// Copy file with error handling
    fn copy_file_with_metadata(&self, source: &Path, destination: &Path) -> Result<()> {
        fs::copy(source, destination).with_context(|| {
            format!("Failed to copy file from {:?} to {:?}", source, destination)
        })?;

        Ok(())
    }

    /// Calculate SHA256 checksum of a file
    fn calculate_checksum(&self, file_path: &Path) -> Result<String> {
        use std::io::Read;

        let mut file = fs::File::open(file_path)
            .with_context(|| format!("Failed to open file for checksum: {:?}", file_path))?;

        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        let mut buffer = vec![0u8; 8192];

        loop {
            let bytes_read = file.read(&mut buffer)
                .with_context(|| format!("Failed to read file for checksum: {:?}", file_path))?;

            if bytes_read == 0 {
                break;
            }

            use std::hash::Hasher;
            hasher.write(&buffer[..bytes_read]);
        }

        use std::hash::Hasher;
        Ok(format!("{:x}", hasher.finish()))
    }

    /// Validate backup integrity
    fn validate_backup(&self, backup_path: &Path, metadata: &BackupMetadata) -> Result<()> {
        debug!("Validating backup at {:?}", backup_path);

        for (original_path, file_info) in &metadata.files {
            let backup_file = backup_path.join(&file_info.backup_path);

            if !backup_file.exists() {
                anyhow::bail!("Backup file missing: {:?}", backup_file);
            }

            // Verify file size
            let actual_size = fs::metadata(&backup_file)
                .with_context(|| format!("Failed to read metadata: {:?}", backup_file))?
                .len();

            if actual_size != file_info.size {
                anyhow::bail!(
                    "Size mismatch for {:?}: expected {}, got {}",
                    original_path,
                    file_info.size,
                    actual_size
                );
            }

            // Verify checksum if available
            if let Some(ref expected_checksum) = file_info.checksum {
                let actual_checksum = self.calculate_checksum(&backup_file)?;

                if &actual_checksum != expected_checksum {
                    anyhow::bail!(
                        "Checksum mismatch for {:?}: expected {}, got {}",
                        original_path,
                        expected_checksum,
                        actual_checksum
                    );
                }
            }
        }

        info!("Backup validation successful");
        Ok(())
    }

    /// Save backup metadata to JSON file
    fn save_metadata(&self, backup_path: &Path, metadata: &BackupMetadata) -> Result<()> {
        let metadata_file = backup_path.join("metadata.json");
        let json = serde_json::to_string_pretty(metadata)
            .context("Failed to serialize backup metadata")?;

        fs::write(&metadata_file, json)
            .with_context(|| format!("Failed to write metadata file: {:?}", metadata_file))?;

        Ok(())
    }

    /// Load backup metadata from JSON file
    fn load_metadata(&self, backup_path: &Path) -> Result<BackupMetadata> {
        let metadata_file = backup_path.join("metadata.json");

        let json = fs::read_to_string(&metadata_file)
            .with_context(|| format!("Failed to read metadata file: {:?}", metadata_file))?;

        let metadata: BackupMetadata = serde_json::from_str(&json)
            .context("Failed to parse backup metadata")?;

        Ok(metadata)
    }

    /// Check if two files differ based on their metadata
    fn files_differ(&self, info1: &BackupFileInfo, info2: &BackupFileInfo) -> bool {
        // Compare sizes
        if info1.size != info2.size {
            return true;
        }

        // Compare checksums if both are available
        match (&info1.checksum, &info2.checksum) {
            (Some(c1), Some(c2)) => c1 != c2,
            _ => {
                // If checksums aren't available, compare modification times
                info1.modified_at != info2.modified_at
            }
        }
    }

    /// Get total size of all backups in bytes
    pub fn get_total_backup_size(&self) -> Result<u64> {
        let backups = self.list_backups()?;
        Ok(backups.iter().map(|b| b.total_size).sum())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::TempDir;

    fn create_test_file(dir: &Path, name: &str, content: &str) -> PathBuf {
        let file_path = dir.join(name);
        let mut file = fs::File::create(&file_path).unwrap();
        file.write_all(content.as_bytes()).unwrap();
        file_path
    }

    #[test]
    fn test_backup_manager_creation() {
        let temp_dir = TempDir::new().unwrap();
        let backup_dir = temp_dir.path().join("backups");

        let manager = BackupManager::new(&backup_dir, 5).unwrap();
        assert!(backup_dir.exists());
    }

    #[test]
    fn test_create_and_restore_backup() {
        let temp_dir = TempDir::new().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let test_file = create_test_file(temp_dir.path(), "test.txt", "test content");

        let manager = BackupManager::new(&backup_dir, 5).unwrap();

        // Create backup
        let backup_id = manager.create_backup(&[test_file.clone()], Some("Test backup".to_string())).unwrap();
        assert!(!backup_id.is_empty());

        // Delete original file
        fs::remove_file(&test_file).unwrap();
        assert!(!test_file.exists());

        // Restore backup
        let restored = manager.restore_backup(&backup_id, false).unwrap();
        assert_eq!(restored, 1);
        assert!(test_file.exists());

        // Verify content
        let content = fs::read_to_string(&test_file).unwrap();
        assert_eq!(content, "test content");
    }

    #[test]
    fn test_list_backups() {
        let temp_dir = TempDir::new().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        let manager = BackupManager::new(&backup_dir, 5).unwrap();

        manager.create_backup(&[test_file.clone()], Some("Backup 1".to_string())).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        manager.create_backup(&[test_file.clone()], Some("Backup 2".to_string())).unwrap();

        let backups = manager.list_backups().unwrap();
        assert_eq!(backups.len(), 2);

        // Should be sorted by creation time, newest first
        assert_eq!(backups[0].description, Some("Backup 2".to_string()));
        assert_eq!(backups[1].description, Some("Backup 1".to_string()));
    }

    #[test]
    fn test_backup_rotation() {
        let temp_dir = TempDir::new().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        let manager = BackupManager::new(&backup_dir, 2).unwrap();

        // Create 3 backups
        manager.create_backup(&[test_file.clone()], None).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        manager.create_backup(&[test_file.clone()], None).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        manager.create_backup(&[test_file.clone()], None).unwrap();

        // Should only keep 2 most recent
        let backups = manager.list_backups().unwrap();
        assert_eq!(backups.len(), 2);
    }

    #[test]
    fn test_diff_backups() {
        let temp_dir = TempDir::new().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let file1 = create_test_file(temp_dir.path(), "file1.txt", "content1");
        let file2 = create_test_file(temp_dir.path(), "file2.txt", "content2");
        let file3 = create_test_file(temp_dir.path(), "file3.txt", "content3");

        let manager = BackupManager::new(&backup_dir, 5).unwrap();

        // First backup with file1 and file2
        let backup1 = manager.create_backup(&[file1.clone(), file2.clone()], None).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));

        // Second backup with file2 (modified) and file3 (new)
        fs::write(&file2, "modified content").unwrap();
        let backup2 = manager.create_backup(&[file2.clone(), file3.clone()], None).unwrap();

        // Compare backups
        let diff = manager.diff_backups(&backup1, &backup2).unwrap();

        assert_eq!(diff.added_files.len(), 1);
        assert!(diff.added_files.contains(&file3));

        assert_eq!(diff.removed_files.len(), 1);
        assert!(diff.removed_files.contains(&file1));

        assert_eq!(diff.modified_files.len(), 1);
        assert!(diff.modified_files.contains(&file2));
    }

    #[test]
    fn test_backup_validation() {
        let temp_dir = TempDir::new().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        let manager = BackupManager::new(&backup_dir, 5).unwrap();

        let backup_id = manager.create_backup(&[test_file], None).unwrap();

        // Validation should succeed
        let backup_path = backup_dir.join(&backup_id);
        let metadata = manager.load_metadata(&backup_path).unwrap();
        assert!(manager.validate_backup(&backup_path, &metadata).is_ok());
    }

    #[test]
    fn test_get_latest_backup() {
        let temp_dir = TempDir::new().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        let manager = BackupManager::new(&backup_dir, 5).unwrap();

        assert!(manager.get_latest_backup_id().unwrap().is_none());

        let backup1 = manager.create_backup(&[test_file.clone()], None).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        let backup2 = manager.create_backup(&[test_file.clone()], None).unwrap();

        let latest = manager.get_latest_backup_id().unwrap();
        assert_eq!(latest, Some(backup2));
    }

    #[test]
    fn test_delete_backup() {
        let temp_dir = TempDir::new().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let test_file = create_test_file(temp_dir.path(), "test.txt", "content");

        let manager = BackupManager::new(&backup_dir, 5).unwrap();

        let backup_id = manager.create_backup(&[test_file], None).unwrap();

        assert_eq!(manager.list_backups().unwrap().len(), 1);

        manager.delete_backup(&backup_id).unwrap();

        assert_eq!(manager.list_backups().unwrap().len(), 0);
    }

    #[test]
    fn test_total_backup_size() {
        let temp_dir = TempDir::new().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let file1 = create_test_file(temp_dir.path(), "file1.txt", "12345");
        let file2 = create_test_file(temp_dir.path(), "file2.txt", "1234567890");

        let manager = BackupManager::new(&backup_dir, 5).unwrap();

        manager.create_backup(&[file1], None).unwrap();
        manager.create_backup(&[file2], None).unwrap();

        let total_size = manager.get_total_backup_size().unwrap();
        assert_eq!(total_size, 15); // 5 + 10 bytes
    }
}