nebulous 0.1.86

A globally distributed container orchestrator
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
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
use crate::query::Query;
use crate::resources::v1::containers::models::V1ContainerStatus;
use crate::resources::v1::volumes::models::V1VolumeDriver;
use sea_orm::{DatabaseConnection, DbErr};
use serde::{Deserialize, Serialize};
use serde_json::from_str;
use std::collections::HashMap;
use std::error::Error;
use std::fs;
use std::path::Path;
use std::process::Command;
use std::process::Stdio;
use tokio::io::AsyncBufReadExt;
use tokio::io::BufReader;
use tokio::process::Command as TokioCommand;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct VolumeConfig {
    pub paths: Vec<VolumePath>,
    #[serde(default = "default_cache_dir")]
    pub cache_dir: String,
    #[serde(default)]
    pub symlinks: Vec<SymlinkConfig>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SymlinkConfig {
    pub source: String,
    pub symlink_path: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct VolumePath {
    pub source: String,
    pub dest: String,
    #[serde(default)]
    pub resync: bool,
    #[serde(default = "default_continuous")]
    pub continuous: bool,
    #[serde(default = "default_volume_driver")]
    pub driver: V1VolumeDriver,
}

fn default_volume_driver() -> V1VolumeDriver {
    V1VolumeDriver::RCLONE_SYNC
}

fn default_continuous() -> bool {
    true
}

// Add this function to provide a default cache directory
fn default_cache_dir() -> String {
    // Use a sensible default location for the cache
    format!("/cache/rclone")
}

impl VolumeConfig {
    /// Read a sync configuration from a file path
    pub fn read_from_file(path: &str) -> Result<Self, Box<dyn Error>> {
        // Check if the config file exists
        if !Path::new(path).exists() {
            return Err(format!("Config file not found: {}", path).into());
        }

        // Read the YAML file
        let yaml_content = fs::read_to_string(path)?;

        // Parse the YAML content
        let config: VolumeConfig = serde_yaml::from_str(&yaml_content)
            .map_err(|e| format!("Failed to parse YAML: {}", e))?;

        Ok(config)
    }

    /// Write the sync configuration to a file path
    pub fn write_to_file(&self, path: &str) -> Result<(), Box<dyn Error>> {
        // Convert the config to YAML
        let yaml_content = serde_yaml::to_string(self)
            .map_err(|e| format!("Failed to serialize to YAML: {}", e))?;

        // Create parent directories if they don't exist
        if let Some(parent) = Path::new(path).parent() {
            fs::create_dir_all(parent)?;
        }

        // Write the YAML content to the file
        fs::write(path, yaml_content)?;

        Ok(())
    }

    /// Create a new empty sync configuration
    pub fn new() -> Self {
        VolumeConfig {
            paths: Vec::new(),
            cache_dir: default_cache_dir(),
            symlinks: Vec::new(),
        }
    }

    /// Add a new path to the sync configuration
    pub fn add_path(
        &mut self,
        source: String,
        dest: String,
        resync: bool,
        driver: V1VolumeDriver,
        continuous: bool,
    ) {
        self.paths.push(VolumePath {
            source,
            dest,
            resync,
            continuous,
            driver,
        });
    }

    /// Remove a path from the sync configuration by index
    pub fn remove_path(&mut self, index: usize) -> Result<(), Box<dyn Error>> {
        if index >= self.paths.len() {
            return Err(format!(
                "Index {} out of bounds (max: {})",
                index,
                self.paths.len() - 1
            )
            .into());
        }

        self.paths.remove(index);
        Ok(())
    }

    /// List all paths in the sync configuration
    pub fn list_paths(&self) -> Vec<(&String, &String, bool, V1VolumeDriver, bool)> {
        self.paths
            .iter()
            .map(|path| {
                (
                    &path.source,
                    &path.dest,
                    path.resync,
                    path.driver.clone(),
                    path.continuous,
                )
            })
            .collect()
    }

    /// Add a symlink configuration
    pub fn add_symlink_config(
        &mut self,
        source: String,
        symlink_path: String,
    ) -> Result<(), Box<dyn Error>> {
        // Check if the source path exists in the configuration
        let source_exists = self.paths.iter().any(|path| path.source == source);

        if !source_exists {
            return Err(format!(
                "Source path '{}' does not exist in the configuration",
                source
            )
            .into());
        }

        // Check if we already have a symlink config for this source path
        for symlink_config in &self.symlinks {
            if symlink_config.source == source && symlink_config.symlink_path == symlink_path {
                return Err(format!(
                    "Symlink from '{}' to '{}' already exists",
                    source, symlink_path
                )
                .into());
            }
        }

        // Create a new symlink config
        self.symlinks.push(SymlinkConfig {
            source,
            symlink_path,
        });

        Ok(())
    }

    /// Remove a symlink from the configuration
    pub fn remove_symlink(
        &mut self,
        source: &str,
        symlink_path: &str,
    ) -> Result<(), Box<dyn Error>> {
        let position = self
            .symlinks
            .iter()
            .position(|config| config.source == source && config.symlink_path == symlink_path);

        if let Some(index) = position {
            self.symlinks.remove(index);
            return Ok(());
        }

        Err(format!("Symlink from '{}' to '{}' not found", source, symlink_path).into())
    }

    /// List all symlinks in the configuration
    pub fn list_all_symlinks(&self) -> Vec<(&str, &str)> {
        self.symlinks
            .iter()
            .map(|config| (config.source.as_str(), config.symlink_path.as_str()))
            .collect()
    }

    /// Get symlinks for a specific source path
    pub fn get_symlinks_for_source(&self, source: &str) -> Vec<&str> {
        self.symlinks
            .iter()
            .filter(|config| config.source == source)
            .map(|config| config.symlink_path.as_str())
            .collect()
    }
}

/// Continuously sync paths from the configuration file at regular intervals
pub async fn execute_continuous_sync(
    config_path: String,
    interval_seconds: u64,
    create_if_missing: bool,
) -> Result<(), Box<dyn Error>> {
    println!(
        "Starting continuous sync from configuration: {}",
        config_path
    );
    println!("Sync interval: {} seconds", interval_seconds);

    // Map to track running processes: (source, dest) -> process
    let mut running_processes: HashMap<(String, String), tokio::process::Child> = HashMap::new();

    loop {
        // Read the current configuration
        let current_config = match VolumeConfig::read_from_file(&config_path) {
            Ok(config) => config,
            Err(e) => {
                if !Path::new(&config_path).exists() && create_if_missing {
                    match create_empty_config(&config_path) {
                        Ok(_) => VolumeConfig::new(),
                        Err(e) => {
                            println!(
                                "Failed to create config file: {}. Will retry on next interval.",
                                e
                            );
                            tokio::time::sleep(tokio::time::Duration::from_secs(interval_seconds))
                                .await;
                            continue;
                        }
                    }
                } else {
                    println!("Error reading config: {}. Will retry on next interval.", e);
                    tokio::time::sleep(tokio::time::Duration::from_secs(interval_seconds)).await;
                    continue;
                }
            }
        };

        {
            let mut finished = vec![];
            for (path_key, child) in &mut running_processes {
                match child.try_wait() {
                    Ok(Some(status)) => {
                        println!(
                            "Rclone subprocess for {} ⟷ {} exited with code: {:?}",
                            path_key.0,
                            path_key.1,
                            status.code()
                        );
                        finished.push(path_key.clone());
                    }
                    Ok(None) => {
                        // Child is still running
                    }
                    Err(e) => {
                        println!(
                            "Error checking status of {} ⟷ {}: {}",
                            path_key.0, path_key.1, e
                        );
                    }
                }
            }
            // Remove any that have exited
            for f in finished {
                running_processes.remove(&f);
            }
        }

        // Check for removed paths and stop their processes
        let mut paths_to_remove = Vec::new();
        for (path_key, process) in &mut running_processes {
            let still_exists = current_config
                .paths
                .iter()
                .any(|path| (&path.source, &path.dest) == (&path_key.0, &path_key.1));

            if !still_exists {
                println!(
                    "Path removed from config: {} ⟷ {}, stopping sync process",
                    path_key.0, path_key.1
                );
                // Attempt to kill the process
                let _ = process.kill();
                paths_to_remove.push(path_key.clone());
            }
        }

        // Remove stopped processes from our map
        for path_key in paths_to_remove {
            running_processes.remove(&path_key);
        }

        // Process each path in the current configuration
        for path in &current_config.paths {
            // Skip paths that are not marked for continuous sync
            if !path.continuous {
                continue;
            }

            let path_key = (path.source.clone(), path.dest.clone());

            // Check if this path needs a new process (new path or resync requested)
            let needs_new_process = path.resync || !running_processes.contains_key(&path_key);

            if needs_new_process {
                // If there's an existing process, stop it first
                if running_processes.contains_key(&path_key) {
                    if let Some(mut process) = running_processes.remove(&path_key) {
                        println!(
                            "Stopping existing sync process for {} ⟷ {}",
                            path_key.0, path_key.1
                        );
                        let _ = process.kill();
                    }
                }

                // Start a new process for this path
                match start_sync_process(path, &current_config.cache_dir).await {
                    Ok(process) => {
                        println!("Started sync process for {} ⟷ {}", path.source, path.dest);
                        running_processes.insert(path_key, process);

                        // If this was a resync operation, mark it as completed
                        if path.resync {
                            // Update the config to set resync to false
                            let mut updated_config = current_config.clone();
                            for p in &mut updated_config.paths {
                                if p.source == path.source && p.dest == path.dest {
                                    p.resync = false;
                                }
                            }
                            // Write the updated config back to file
                            if let Err(e) = updated_config.write_to_file(&config_path) {
                                println!("Failed to update config after resync: {}", e);
                            }
                        }
                    }
                    Err(e) => {
                        println!(
                            "Failed to start sync process for {} ⟷ {}: {}",
                            path.source, path.dest, e
                        );
                    }
                }
            }
        }

        // Report status
        println!(
            "Currently managing {} sync processes. Waiting for next check...",
            running_processes.len()
        );

        // Sleep for the specified interval
        tokio::time::sleep(tokio::time::Duration::from_secs(interval_seconds)).await;
    }
}
/// Start a new rclone sync process for a path
async fn start_sync_process(
    path: &VolumePath,
    _cache_dir: &str,
) -> Result<tokio::process::Child, Box<dyn Error>> {
    // Build the rclone command
    let mut cmd = TokioCommand::new("rclone");

    // Normalize S3 paths
    let source = normalize_s3_path(&path.source);
    let dest = normalize_s3_path(&path.dest);

    // Create source and destination directories if they don't exist
    ensure_path_exists(&source).await?;
    ensure_path_exists(&dest).await?;

    // Decide which rclone subcommand to use based on the driver
    if path.driver == V1VolumeDriver::RCLONE_BISYNC {
        // Use bisync for bidirectional sync
        cmd.arg("bisync");
        cmd.arg(&source);
        cmd.arg(&dest);

        cmd.arg("--resync");
    } else if path.driver == V1VolumeDriver::RCLONE_COPY {
        // Use copy for unidirectional copy
        cmd.arg("copy");
        cmd.arg(&source);
        cmd.arg(&dest);
    } else {
        // Use sync for unidirectional sync
        cmd.arg("sync");
        cmd.arg(&source);
        cmd.arg(&dest);
    }

    // Add resync flag if needed and it's a bidirectional sync
    if path.resync && path.driver == V1VolumeDriver::RCLONE_BISYNC {
        cmd.arg("--resync");
    }

    // Exclude common Python cache directories
    cmd.arg("--exclude").arg("__pycache__/**");

    // cmd.arg("--create-empty-src-dirs");

    // // Add common options
    // cmd.arg("--verbose");
    // cmd.arg("--fast-list");

    // // Add cache directory
    // cmd.arg("--cache-dir");
    // cmd.arg(cache_dir);

    // Add resilient mode for bidirectional sync
    if path.driver == V1VolumeDriver::RCLONE_BISYNC {
        // cmd.arg("--resilient");

        // Add --force flag to help with empty directory issues
        cmd.arg("--force");
    }

    // Spawn the process

    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());

    let mut child = cmd.spawn()?;

    if let Some(stdout) = child.stdout.take() {
        let source_clone = path.source.clone();
        let dest_clone = path.dest.clone();
        tokio::spawn(async move {
            let mut reader = BufReader::new(stdout).lines();
            while let Ok(Some(line)) = reader.next_line().await {
                println!(
                    "[rclone stdout: {} ⟷ {}] {}",
                    source_clone, dest_clone, line
                );
            }
        });
    }
    if let Some(stderr) = child.stderr.take() {
        let source_clone = path.source.clone();
        let dest_clone = path.dest.clone();
        tokio::spawn(async move {
            let mut reader = BufReader::new(stderr).lines();
            while let Ok(Some(line)) = reader.next_line().await {
                println!(
                    "[rclone stderr: {} ⟷ {}] {}",
                    source_clone, dest_clone, line
                );
            }
        });
    }

    Ok(child)
}

/// Normalize an S3 path to ensure it uses the format expected by rclone (s3:bucket/path)
fn normalize_s3_path(path: &str) -> String {
    if path.starts_with("s3://") {
        // Convert s3://bucket/path to s3:bucket/path
        format!("s3:{}", &path[5..])
    } else {
        // Already in the correct format or not an S3 path
        path.to_string()
    }
}

/// Execute rclone bisync for all paths in the configuration
pub async fn execute_sync(
    config_path: String,
    create_if_missing: bool,
) -> Result<(), Box<dyn Error>> {
    println!("Reading sync configuration from: {}", config_path);

    if !Path::new(&config_path).exists() {
        if create_if_missing {
            create_empty_config(&config_path)?;
        } else {
            return Err(format!("Config file not found: {}", config_path).into());
        }
    }

    // Use the read_from_file method
    let config = VolumeConfig::read_from_file(&config_path)?;

    if config.paths.is_empty() {
        println!("No paths to sync found in the configuration file.");
        return Ok(());
    }

    println!("Found {} paths to sync", config.paths.len());

    // Process each path
    for (index, path) in config.paths.iter().enumerate() {
        let sync_type = if path.driver == V1VolumeDriver::RCLONE_BISYNC {
            "Bidirectional"
        } else {
            "Unidirectional"
        };

        println!(
            "[{}/{}] {} syncing between {} and {}",
            index + 1,
            config.paths.len(),
            sync_type,
            path.source,
            path.dest
        );

        // Normalize S3 paths
        let source = normalize_s3_path(&path.source);
        let dest = normalize_s3_path(&path.dest);

        // Create source and destination directories if they don't exist
        ensure_path_exists(&source).await?;
        ensure_path_exists(&dest).await?;

        // Build the rclone command
        let mut cmd = Command::new("rclone");

        // Normalize S3 paths
        let source = normalize_s3_path(&path.source);
        let dest = normalize_s3_path(&path.dest);

        if path.driver == V1VolumeDriver::RCLONE_BISYNC {
            cmd.arg("bisync");
            cmd.arg(&source);
            cmd.arg(&dest);

            // Add --resync flag if needed
            if path.resync {
                cmd.arg("--resync");
            }

            // Add --force flag to help with empty directory issues
            cmd.arg("--force");
        } else if path.driver == V1VolumeDriver::RCLONE_COPY {
            // For rclone copy
            cmd.arg("copy");
            cmd.arg(&source);
            cmd.arg(&dest);
        } else {
            // Default to unidirectional sync
            cmd.arg("sync");
            cmd.arg(&source);
            cmd.arg(&dest);
        }

        // Add common options
        // cmd.arg("--verbose");
        // cmd.arg("--fast-list");
        // cmd.arg("--create-empty-src-dirs");

        // Exclude common Python cache directories
        cmd.arg("--exclude").arg("__pycache__/**");

        // Add cache directory
        // cmd.arg("--cache-dir");
        // cmd.arg(&config.cache_dir);

        // Execute the command
        let output = cmd.output()?;
        if output.status.success() {
            println!(
                "Successfully synced between {} and {}",
                path.source, path.dest
            );

            // If this was a resync operation, mark it as completed
            if path.resync && path.driver == V1VolumeDriver::RCLONE_BISYNC {
                // Read the config again to get the latest version
                let mut updated_config = VolumeConfig::read_from_file(&config_path)?;
                if index < updated_config.paths.len() {
                    updated_config.paths[index].resync = false;
                    updated_config.write_to_file(&config_path)?;
                }
            }
        } else {
            let error = String::from_utf8_lossy(&output.stderr);
            println!("Failed to sync: {}", error);

            // Check if this is the "empty prior listing" error and we need to resync
            if error.contains("empty prior Path1 listing")
                || error.contains("Must run --resync to recover")
            {
                println!("Detected need for resync. Attempting to resync...");

                // Create a new command with --resync flag
                let mut resync_cmd = Command::new("rclone");
                resync_cmd.arg("bisync");
                resync_cmd.arg(&source);
                resync_cmd.arg(&dest);
                resync_cmd.arg("--resync");
                resync_cmd.arg("--force");
                // resync_cmd.arg("--verbose");
                // resync_cmd.arg("--fast-list");
                // resync_cmd.arg("--create-empty-src-dirs");
                // resync_cmd.arg("--cache-dir");
                // resync_cmd.arg(&config.cache_dir);

                // Execute the resync command
                let resync_output = resync_cmd.output()?;
                if resync_output.status.success() {
                    println!("Resync successful between {} and {}", source, dest);
                } else {
                    let resync_error = String::from_utf8_lossy(&resync_output.stderr);
                    println!("Resync failed: {}", resync_error);
                }
            }
        }
    }

    println!("Sync operation completed");
    Ok(())
}

/// Create a new empty sync configuration file
pub fn create_empty_config(path: &str) -> Result<(), Box<dyn Error>> {
    let config = VolumeConfig::new();

    // Write the empty config to the file
    config.write_to_file(path)?;

    println!("Created empty sync configuration at: {}", path);
    Ok(())
}

/// Create a new example sync configuration file with various sync types
pub fn create_example_config(path: &str) -> Result<(), Box<dyn Error>> {
    let mut config = VolumeConfig::new();

    // Add example for bidirectional continuous sync
    config.add_path(
        "/path/to/local/directory1".to_string(),
        "s3:your-bucket/directory1".to_string(),
        true,                          // Initial sync should use resync
        V1VolumeDriver::RCLONE_BISYNC, // bidirectional
        true,                          // continuous
    );

    // Add example for unidirectional one-time sync
    config.add_path(
        "/path/to/local/directory2".to_string(),
        "s3:your-bucket/directory2".to_string(),
        false,                       // No resync needed for unidirectional
        V1VolumeDriver::RCLONE_SYNC, // unidirectional
        false,                       // one-time
    );

    // Write the config to the file
    config.write_to_file(path)?;

    println!("Created example sync configuration at: {}", path);
    Ok(())
}

/// Add a new path to an existing sync configuration
pub fn add_sync_path(
    config_path: &str,
    source: String,
    dest: String,
    volume_type: V1VolumeDriver,
    continuous: bool,
) -> Result<(), Box<dyn Error>> {
    // Read the existing config or create a new one if it doesn't exist
    let mut config = if Path::new(config_path).exists() {
        VolumeConfig::read_from_file(config_path)?
    } else {
        VolumeConfig::new()
    };

    // Add the new path with resync set to true for initial bidirectional sync
    let resync = volume_type.clone() == V1VolumeDriver::RCLONE_BISYNC; // Only set resync true if bidirectional
    config.add_path(
        source.clone(),
        dest.clone(),
        resync,
        volume_type.clone(),
        continuous,
    );

    // Write the updated config back to the file
    config.write_to_file(config_path)?;

    let sync_type = if volume_type.clone() == V1VolumeDriver::RCLONE_BISYNC {
        "bidirectional"
    } else {
        "unidirectional"
    };
    let sync_mode = if continuous { "continuous" } else { "once" };

    println!(
        "Added {} {} sync path between {} and {}",
        sync_type, sync_mode, source, dest
    );
    Ok(())
}

/// Remove a path from an existing sync configuration by index
pub fn remove_sync_path(config_path: &str, index: usize) -> Result<(), Box<dyn Error>> {
    // Read the existing config
    let mut config = VolumeConfig::read_from_file(config_path)?;

    // Get the path that will be removed (for the message)
    let path_to_remove = if index < config.paths.len() {
        // Clone the strings to avoid the borrow conflict
        Some((
            config.paths[index].source.clone(),
            config.paths[index].dest.clone(),
        ))
    } else {
        None
    };

    // Remove the path
    config.remove_path(index)?;

    // Write the updated config back to the file
    config.write_to_file(config_path)?;

    if let Some((source, destination)) = path_to_remove {
        println!("Removed sync path between {} and {}", source, destination);
    }

    Ok(())
}

/// List all paths in a sync configuration
pub fn list_sync_paths(config_path: &str) -> Result<(), Box<dyn Error>> {
    // Read the existing config
    let config = VolumeConfig::read_from_file(config_path)?;

    if config.paths.is_empty() {
        println!("No sync paths found in the configuration.");
        return Ok(());
    }

    println!("Sync paths in {}:", config_path);
    for (i, (source, destination, resync, volume_type, continuous)) in
        config.list_paths().iter().enumerate()
    {
        let direction = if *volume_type == V1VolumeDriver::RCLONE_BISYNC {
            "bidirectional"
        } else {
            "unidirectional"
        };
        let mode = if *continuous { "continuous" } else { "once" };
        let resync_status = if *resync && *volume_type == V1VolumeDriver::RCLONE_BISYNC {
            " (resync pending)"
        } else {
            ""
        };

        println!(
            "[{}] {} ⟷ {} ({}, {}){}",
            i, source, destination, direction, mode, resync_status
        );
    }

    Ok(())
}

/// ------------------------------------------------------------------------------------------------
/// Symlinks
/// ------------------------------------------------------------------------------------------------

/// Add a symlink to a path in the configuration
pub fn add_symlink_to_path(
    config_path: &str,
    path_index: usize,
    symlink_path: &str,
) -> Result<(), Box<dyn Error>> {
    // Read the existing config
    let mut config = VolumeConfig::read_from_file(config_path)?;

    // Add the symlink to the configuration
    let source = config.paths[path_index].source.clone();
    config.add_symlink_config(source, symlink_path.to_string())?;

    // Write the updated config back to the file
    config.write_to_file(config_path)?;

    println!(
        "Added symlink {} to path index {}",
        symlink_path, path_index
    );
    Ok(())
}

/// Remove a symlink from a path in the configuration
pub fn remove_symlink_from_path(
    config_path: &str,
    path_index: usize,
    symlink_index: usize,
) -> Result<(), Box<dyn Error>> {
    // Read the existing config
    let mut config = VolumeConfig::read_from_file(config_path)?;

    // Get the source path for the specified path index
    if path_index >= config.paths.len() {
        return Err(format!("Path index {} out of bounds", path_index).into());
    }
    let source = config.paths[path_index].source.clone();

    // Find all symlinks for this source path
    let matching_symlinks: Vec<_> = config
        .symlinks
        .iter()
        .filter(|s| s.source == source)
        .collect();

    if symlink_index >= matching_symlinks.len() {
        return Err(format!("Symlink index {} out of bounds", symlink_index).into());
    }

    // Get the symlink path before removing it
    let symlink_path = matching_symlinks[symlink_index].symlink_path.clone();

    // Remove the symlink
    config.remove_symlink(&source, &symlink_path)?;

    // Write the updated config back to the file
    config.write_to_file(config_path)?;

    println!(
        "Removed symlink {} from path index {}",
        symlink_path, path_index
    );
    Ok(())
}

/// List all symlinks for a path in the configuration
pub fn list_symlinks_for_path(config_path: &str, path_index: usize) -> Result<(), Box<dyn Error>> {
    // Read the existing config
    let config = VolumeConfig::read_from_file(config_path)?;

    // Get the source path for the specified path index
    if path_index >= config.paths.len() {
        return Err(format!("Path index {} out of bounds", path_index).into());
    }
    let source = &config.paths[path_index].source;

    // Get the symlinks for the specified path
    let symlinks = config.get_symlinks_for_source(source);

    if symlinks.is_empty() {
        println!("No symlinks found for path index {}", path_index);
        return Ok(());
    }

    println!("Symlinks for path index {}:", path_index);
    for (i, symlink) in symlinks.iter().enumerate() {
        println!("[{}] {}", i, symlink);
    }

    Ok(())
}

/// Create symlinks defined in the configuration
pub fn create_symlinks_from_config(config_path: &str) -> Result<(), Box<dyn Error>> {
    // Read the existing config
    let config = VolumeConfig::read_from_file(config_path)?;

    let mut created_count = 0;
    let mut error_count = 0;

    // Process each symlink configuration
    for symlink_config in &config.symlinks {
        // Skip remote paths
        if symlink_config.source.contains(":") {
            println!(
                "Skipping symlink for remote path: {}",
                symlink_config.source
            );
            continue;
        }

        // Create parent directories for the symlink if they don't exist
        if let Some(parent) = Path::new(&symlink_config.symlink_path).parent() {
            if let Err(e) = fs::create_dir_all(parent) {
                println!(
                    "Failed to create parent directories for symlink {}: {}",
                    symlink_config.symlink_path, e
                );
                error_count += 1;
                continue;
            }
        }

        // Remove existing symlink if it exists
        if Path::new(&symlink_config.symlink_path).exists() {
            if Path::new(&symlink_config.symlink_path).is_symlink() {
                if let Err(e) = fs::remove_file(&symlink_config.symlink_path) {
                    println!(
                        "Failed to remove existing symlink {}: {}",
                        symlink_config.symlink_path, e
                    );
                    error_count += 1;
                    continue;
                }
            } else {
                println!(
                    "Destination path exists and is not a symlink: {}",
                    symlink_config.symlink_path
                );
                error_count += 1;
                continue;
            }
        }

        // Create the symlink
        let result = {
            #[cfg(unix)]
            {
                std::os::unix::fs::symlink(&symlink_config.source, &symlink_config.symlink_path)
            }
            #[cfg(windows)]
            {
                match fs::metadata(&symlink_config.source) {
                    Ok(metadata) => {
                        if metadata.is_dir() {
                            std::os::windows::fs::symlink_dir(
                                &symlink_config.source,
                                &symlink_config.symlink_path,
                            )
                        } else {
                            std::os::windows::fs::symlink_file(
                                &symlink_config.source,
                                &symlink_config.symlink_path,
                            )
                        }
                    }
                    Err(e) => Err(e),
                }
            }
        };

        match result {
            Ok(_) => {
                println!(
                    "Created symlink from {} to {}",
                    symlink_config.source, symlink_config.symlink_path
                );
                created_count += 1;
            }
            Err(e) => {
                println!(
                    "Failed to create symlink from {} to {}: {}",
                    symlink_config.source, symlink_config.symlink_path, e
                );
                error_count += 1;
            }
        }
    }

    println!(
        "Symlink creation completed: {} created, {} failed",
        created_count, error_count
    );
    Ok(())
}

/// Add a symlink to the configuration
pub fn add_symlink(
    config_path: &str,
    source: &str,
    symlink_path: &str,
) -> Result<(), Box<dyn Error>> {
    // Read the existing config
    let mut config = VolumeConfig::read_from_file(config_path)?;

    // Add the symlink to the configuration
    config.add_symlink_config(source.to_string(), symlink_path.to_string())?;

    // Write the updated config back to the file
    config.write_to_file(config_path)?;

    println!("Added symlink from {} to {}", source, symlink_path);
    Ok(())
}

/// Remove a symlink from the configuration
pub fn remove_symlink(
    config_path: &str,
    source: &str,
    symlink_path: &str,
) -> Result<(), Box<dyn Error>> {
    // Read the existing config
    let mut config = VolumeConfig::read_from_file(config_path)?;

    // Remove the symlink from the configuration
    config.remove_symlink(source, symlink_path)?;

    // Write the updated config back to the file
    config.write_to_file(config_path)?;

    println!("Removed symlink from {} to {}", source, symlink_path);
    Ok(())
}

/// List all symlinks in the configuration
pub fn list_symlinks(config_path: &str) -> Result<(), Box<dyn Error>> {
    // Read the existing config
    let config = VolumeConfig::read_from_file(config_path)?;

    let all_symlinks = config.list_all_symlinks();

    if all_symlinks.is_empty() {
        println!("No symlinks found in the configuration.");
        return Ok(());
    }

    println!("Symlinks in the configuration:");
    for (i, (source, symlink_path)) in all_symlinks.iter().enumerate() {
        println!("[{}] {} -> {}", i, source, symlink_path);
    }

    Ok(())
}

/// List symlinks for a specific source path
pub fn list_symlinks_for_source(config_path: &str, source: &str) -> Result<(), Box<dyn Error>> {
    // Read the existing config
    let config = VolumeConfig::read_from_file(config_path)?;

    let symlinks = config.get_symlinks_for_source(source);

    if symlinks.is_empty() {
        println!("No symlinks found for source path: {}", source);
        return Ok(());
    }

    println!("Symlinks for source path: {}", source);
    for (i, symlink_path) in symlinks.iter().enumerate() {
        println!("[{}] {}", i, symlink_path);
    }

    Ok(())
}

/// Execute one-time sync for non-continuous paths in the configuration
pub async fn execute_non_continuous_sync(
    config_path: &str,
    create_if_missing: bool,
) -> Result<(), Box<dyn Error>> {
    println!(
        "Executing one-time sync for non-continuous paths from: {}",
        config_path
    );

    if !Path::new(config_path).exists() {
        if create_if_missing {
            create_empty_config(config_path)?;
        } else {
            return Err(format!("Config file not found: {}", config_path).into());
        }
    }

    // Read the configuration
    let config = VolumeConfig::read_from_file(config_path)?;

    // Filter out non-continuous paths
    let once_paths: Vec<_> = config
        .paths
        .iter()
        .filter(|path| !path.continuous)
        .collect();

    if once_paths.is_empty() {
        println!("No non-continuous paths found in the configuration.");
        return Ok(());
    }

    println!("Found {} non-continuous paths to sync", once_paths.len());

    // Process each non-continuous path
    for (index, path) in once_paths.iter().enumerate() {
        let sync_type = if path.driver.clone() == V1VolumeDriver::RCLONE_BISYNC {
            "Bidirectional"
        } else {
            "Unidirectional"
        };

        println!(
            "[{}/{}] {} syncing between {} and {}",
            index + 1,
            once_paths.len(),
            sync_type,
            path.source,
            path.dest
        );

        // Normalize S3 paths
        let source = normalize_s3_path(&path.source);
        let dest = normalize_s3_path(&path.dest);

        // Create source and destination directories if they don't exist
        ensure_path_exists(&source).await?;
        ensure_path_exists(&dest).await?;

        // Build the rclone command
        let mut cmd = Command::new("rclone");

        // Normalize S3 paths
        let source = normalize_s3_path(&path.source);
        let dest = normalize_s3_path(&path.dest);

        if path.driver.clone() == V1VolumeDriver::RCLONE_BISYNC {
            cmd.arg("bisync");
            cmd.arg(&source);
            cmd.arg(&dest);

            cmd.arg("--resync");

            // Add --force flag to help with empty directory issues
            cmd.arg("--force");
        } else {
            cmd.arg("sync");
            cmd.arg(&source);
            cmd.arg(&dest);
        }

        // Exclude common Python cache directories
        cmd.arg("--exclude").arg("__pycache__/**");

        // Add common options
        // cmd.arg("--verbose");
        // cmd.arg("--fast-list");
        // cmd.arg("--create-empty-src-dirs");

        // Add cache directory
        // cmd.arg("--cache-dir");
        // cmd.arg(&config.cache_dir);

        // Execute the command
        let output = cmd.output()?;
        if output.status.success() {
            println!("Successfully synced between {} and {}", source, dest);

            // If this was a resync operation, mark it as completed
            if path.resync && path.driver.clone() == V1VolumeDriver::RCLONE_BISYNC {
                // Find the index in the original config
                if let Some(original_index) = config
                    .paths
                    .iter()
                    .position(|p| p.source == path.source && p.dest == path.dest)
                {
                    // Read the config again to get the latest version
                    let mut updated_config = VolumeConfig::read_from_file(config_path)?;
                    if original_index < updated_config.paths.len() {
                        updated_config.paths[original_index].resync = false;
                        updated_config.write_to_file(config_path)?;
                    }
                }
            }
        } else {
            let error = String::from_utf8_lossy(&output.stderr);
            println!("Failed to sync: {}", error);

            // Check if this is the "empty prior listing" error and we need to resync
            if error.contains("empty prior Path1 listing")
                || error.contains("Must run --resync to recover")
            {
                println!("Detected need for resync. Attempting to resync...");

                // Create a new command with --resync flag
                let mut resync_cmd = Command::new("rclone");
                resync_cmd.arg("bisync");
                resync_cmd.arg(&source);
                resync_cmd.arg(&dest);
                resync_cmd.arg("--resync");
                resync_cmd.arg("--force");
                // resync_cmd.arg("--verbose");
                // resync_cmd.arg("--fast-list");
                // resync_cmd.arg("--create-empty-src-dirs");
                // resync_cmd.arg("--cache-dir");
                // resync_cmd.arg(&config.cache_dir);

                // Execute the resync command
                let resync_output = resync_cmd.output()?;
                if resync_output.status.success() {
                    println!("Resync successful between {} and {}", source, dest);
                } else {
                    let resync_error = String::from_utf8_lossy(&resync_output.stderr);
                    println!("Resync failed: {}", resync_error);
                }
            }
        }
    }

    println!("Non-continuous sync operation completed");
    Ok(())
}

/// ------------------------------------------------------------------------------------------------
/// Sync checkers
/// ------------------------------------------------------------------------------------------------

/// Checks if two volume configs both bidirectionally sync from the same S3 path or child paths.
///
/// Returns true if both configs have at least one bidirectional sync path that
/// shares the same S3 path or where one path is a child of the other.
pub fn has_overlapping_s3_bidirectional_sync(
    config1: &VolumeConfig,
    config2: &VolumeConfig,
) -> bool {
    // Get all bidirectional paths with S3 sources from both configs
    let config1_s3_paths: Vec<String> = config1
        .paths
        .iter()
        .filter(|path| {
            path.driver.clone() == V1VolumeDriver::RCLONE_BISYNC
                && (path.source.starts_with("s3://") || path.source.starts_with("s3:"))
        })
        .map(|path| normalize_s3_path(&path.source))
        .collect();

    let config2_s3_paths: Vec<String> = config2
        .paths
        .iter()
        .filter(|path| {
            path.driver.clone() == V1VolumeDriver::RCLONE_BISYNC
                && (path.source.starts_with("s3://") || path.source.starts_with("s3:"))
        })
        .map(|path| normalize_s3_path(&path.source))
        .collect();

    // Check for overlapping paths
    for path1 in &config1_s3_paths {
        for path2 in &config2_s3_paths {
            // Check if paths are the same
            if path1 == path2 {
                return true;
            }

            // Check if one path is a child of the other
            // We need to ensure we're comparing paths with trailing slashes to avoid partial matches
            let path1_normalized = if path1.ends_with('/') {
                path1.to_string()
            } else {
                format!("{}/", path1)
            };

            let path2_normalized = if path2.ends_with('/') {
                path2.to_string()
            } else {
                format!("{}/", path2)
            };

            if path1_normalized.starts_with(&path2_normalized)
                || path2_normalized.starts_with(&path1_normalized)
            {
                return true;
            }
        }
    }

    false
}

/// Checks if a volume configuration has overlapping S3 bidirectional syncs with any active container in the database.
/// Active containers are those with status "running", "queued", "started", or "waiting".
///
/// Returns a vector of container IDs that have overlapping configurations.
pub async fn find_active_containers_with_overlapping_s3_sync(
    db: &DatabaseConnection,
    new_config: &VolumeConfig,
    exclude_container_id: Option<&str>,
) -> Result<Vec<String>, DbErr> {
    // Get all containers from the database
    let all_containers = Query::find_all_containers(db).await?;

    let mut overlapping_container_ids = Vec::new();

    for container in all_containers {
        // Skip the container we're updating (if provided)
        if let Some(exclude_id) = exclude_container_id {
            if container.id == exclude_id {
                continue;
            }
        }

        // Check if container has an active status
        if let Some(status_json) = &container.status {
            // Deserialize the JSON to V1ContainerStatus
            match serde_json::from_value::<V1ContainerStatus>(status_json.clone()) {
                Ok(status) => {
                    let status_str = match status.status {
                        Some(s) => s.to_lowercase(),
                        None => continue, // Skip if status is None
                    };

                    if ![
                        "running",
                        "queued",
                        "started",
                        "waiting",
                        "pending",
                        "suspended",
                    ]
                    .contains(&status_str.as_str())
                    {
                        continue; // Skip containers that aren't active
                    }
                }
                Err(_) => continue, // Skip if deserialization fails
            }
        } else {
            continue; // Skip containers with no status
        }

        // Parse the volumes JSON from the database
        if let Some(volumes_json) = &container.volumes {
            match from_str::<VolumeConfig>(&volumes_json.to_string()) {
                Ok(existing_config) => {
                    // Check for overlapping S3 bidirectional syncs
                    if has_overlapping_s3_bidirectional_sync(new_config, &existing_config) {
                        overlapping_container_ids.push(container.id.clone());
                    }
                }
                Err(_) => {
                    // Skip containers with invalid volume configurations
                    continue;
                }
            }
        }
    }

    Ok(overlapping_container_ids)
}

/// Validates that a volume configuration doesn't overlap with any existing container's S3 bidirectional syncs.
///
/// Returns Ok(()) if no overlaps are found, or an error with details about the overlapping containers.
pub async fn validate_no_overlapping_s3_syncs(
    db: &DatabaseConnection,
    new_config: &VolumeConfig,
    exclude_container_id: Option<&str>,
) -> Result<(), DbErr> {
    let overlapping_containers =
        find_active_containers_with_overlapping_s3_sync(db, new_config, exclude_container_id)
            .await?;

    if overlapping_containers.is_empty() {
        Ok(())
    } else {
        Err(DbErr::Custom(format!(
            "The volume configuration has overlapping S3 bidirectional syncs with existing containers: {}",
            overlapping_containers.join(", ")
        )))
    }
}

/// Sets up rclone configuration from environment variables if available
/// Returns a temporary file handle if a config was created (to keep it alive)
pub fn setup_rclone_config_from_env() -> Result<Option<std::fs::File>, Box<dyn Error>> {
    // Check if we have rclone config environment variables
    let has_s3_env = std::env::var("RCLONE_CONFIG_S3REMOTE_TYPE").is_ok()
        || std::env::var("AWS_ACCESS_KEY_ID").is_ok();

    if has_s3_env {
        // Create a temporary rclone config file
        let temp_path = std::env::temp_dir().join("rclone_config.conf");
        let mut temp_file = std::fs::File::create(&temp_path)?;
        use std::io::Write;

        // Write S3 remote configuration
        writeln!(temp_file, "[s3]")?;
        writeln!(temp_file, "type = s3")?;

        // Add region if available
        if let Ok(region) = std::env::var("RCLONE_CONFIG_S3REMOTE_REGION") {
            writeln!(temp_file, "region = {}", region)?;
        } else if let Ok(region) = std::env::var("AWS_REGION") {
            writeln!(temp_file, "region = {}", region)?;
        }

        // Add provider if available
        if let Ok(provider) = std::env::var("RCLONE_CONFIG_S3REMOTE_PROVIDER") {
            writeln!(temp_file, "provider = {}", provider)?;
        }

        // Add env_auth if available
        if let Ok(env_auth) = std::env::var("RCLONE_CONFIG_S3REMOTE_ENV_AUTH") {
            writeln!(temp_file, "env_auth = {}", env_auth)?;
        } else {
            // Default to true if AWS credentials are in environment
            if std::env::var("AWS_ACCESS_KEY_ID").is_ok()
                && std::env::var("AWS_SECRET_ACCESS_KEY").is_ok()
            {
                writeln!(temp_file, "env_auth = true")?;
            }
        }

        // Set the RCLONE_CONFIG environment variable to point to our temporary file
        std::env::set_var("RCLONE_CONFIG", temp_path.to_string_lossy().to_string());

        println!("Created temporary rclone configuration from environment variables");
        Ok(Some(temp_file))
    } else {
        Ok(None)
    }
}

/// Create a directory in S3 if it doesn't exist
async fn create_s3_directory(path: &str) -> Result<(), Box<dyn Error>> {
    // Extract bucket and prefix from s3:bucket/path format
    let path = path.trim_start_matches("s3:");
    let parts: Vec<&str> = path.splitn(2, '/').collect();

    if parts.len() < 2 {
        // Just a bucket name, no need to create anything
        return Ok(());
    }

    let bucket = parts[0];
    let prefix = parts[1];

    // Ensure the prefix ends with a slash to properly represent a directory
    let directory_prefix = if prefix.ends_with('/') {
        prefix.to_string()
    } else {
        format!("{}/", prefix)
    };

    println!("Checking S3 directory: s3:{}/{}", bucket, directory_prefix);

    // First try to list the directory to see if it exists
    let list_cmd = TokioCommand::new("rclone")
        .arg("lsf")
        .arg(format!("s3:{}/{}", bucket, directory_prefix))
        .output()
        .await?;

    // If listing succeeds, the directory exists or we at least have read access
    if list_cmd.status.success() {
        return Ok(());
    }

    // If we get here, try to create the directory but don't fail if we get a permission error
    println!(
        "Attempting to create S3 directory: s3:{}/{}",
        bucket, directory_prefix
    );

    let temp_dir = tempfile::tempdir()?;
    let temp_file_path = temp_dir.path().join(".rclone_directory_marker");
    std::fs::write(&temp_file_path, "")?;

    let create_cmd = TokioCommand::new("rclone")
        .arg("copy")
        .arg(&temp_file_path)
        .arg(format!("s3:{}/{}", bucket, directory_prefix))
        .output()
        .await?;

    if !create_cmd.status.success() {
        let error = String::from_utf8_lossy(&create_cmd.stderr);
        // If it's a permission error, log it but don't fail
        if error.contains("Forbidden") || error.contains("status code: 403") {
            println!("Note: Unable to create S3 directory marker due to permissions (this may be expected): s3:{}/{}", bucket, directory_prefix);
            return Ok(());
        }
        // For other errors, return the error
        return Err(format!("Failed to create S3 directory: {}", error).into());
    }

    Ok(())
}

/// Ensure a path exists, creating it if necessary (works for both local and S3 paths)
async fn ensure_path_exists(path: &str) -> Result<(), Box<dyn Error>> {
    let normalized_path = normalize_s3_path(path);

    if normalized_path.starts_with("s3:") {
        // S3 path
        create_s3_directory(&normalized_path).await?;
    } else if !Path::new(&normalized_path).exists() {
        // Local path
        println!("Creating local directory: {}", normalized_path);
        fs::create_dir_all(&normalized_path)?;
    }

    Ok(())
}

/// Check if two paths are in sync using rclone.
/// Check if two paths are in sync using rclone.
pub async fn check_paths(source: &str, dest: &str) -> Result<bool, Box<dyn std::error::Error>> {
    use std::process::Stdio;
    use tokio::process::Command;

    // Fail immediately if no RCLONE_CONFIG is set
    let config_path = match std::env::var("RCLONE_CONFIG") {
        Ok(path) => path,
        Err(_) => {
            return Err(
                "No RCLONE_CONFIG environment variable set - cannot proceed with rclone check!"
                    .into(),
            );
        }
    };

    let output = Command::new("rclone")
        .arg("check")
        // Force using our config:
        .arg("--config")
        .arg(&config_path)
        .arg(source)
        .arg(dest)
        .arg("--one-way") // or omit if you want a two-way check
        // Exclude common Python cache directories
        .arg("--exclude")
        .arg("__pycache__/**")
        .stderr(Stdio::piped())
        .stdout(Stdio::piped())
        .output()
        .await?;

    // Print logs
    println!("stdout:\n{}", String::from_utf8_lossy(&output.stdout));
    eprintln!("stderr:\n{}", String::from_utf8_lossy(&output.stderr));

    // A 0 exit code means everything is in sync, non-zero means differences or errors.
    Ok(output.status.success())
}