relfa 0.1.2

A gentle digital gravedigger to lovingly archive your old files.
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
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use std::fs;
use std::path::{Path, PathBuf};

use crate::config::Config;
use crate::scanner::StaleItem;

pub struct Archiver {
    config: Config,
}

#[derive(Debug)]
pub struct ArchivedItem {}

impl Archiver {
    pub fn new(config: Config) -> Self {
        Self { config }
    }

    pub fn archive_item_with_note(
        &self,
        item: &StaleItem,
        note: Option<&str>,
    ) -> Result<ArchivedItem> {
        let now = Utc::now();

        let created_time = self.get_creation_time(&item.path)?;
        let modified_time = item.last_modified;
        let archived_time = now;

        // Find all subdirs that need original files
        let mut original_subdirs = self.find_original_subdirs()?;

        // Set proper times for each subdir
        for (subdir_name, time) in original_subdirs.iter_mut() {
            if self.config.path_format.created_subdir.get_name() == Some(subdir_name) {
                *time = created_time;
            } else if self.config.path_format.modified_subdir.get_name() == Some(subdir_name) {
                *time = modified_time;
            } else if self.config.path_format.archived_subdir.get_name() == Some(subdir_name) {
                *time = archived_time;
            }
        }

        let mut primary_path = None;
        let mut created_paths = std::collections::HashMap::new();

        // Create original files in all required subdirs
        for (i, (subdir_name, time)) in original_subdirs.iter().enumerate() {
            let target_path = self.create_path_for_subdir(subdir_name, &item.name, *time)?;
            self.ensure_directory_exists(target_path.parent().unwrap())?;

            if i == 0 {
                // Move the original file to the first location
                fs::rename(&item.path, &target_path).context("Failed to move item to graveyard")?;
                primary_path = Some(target_path.clone());
            } else {
                // Copy to additional locations
                if item.path.is_dir() {
                    copy_dir_all(primary_path.as_ref().unwrap(), &target_path)?;
                } else {
                    fs::copy(primary_path.as_ref().unwrap(), &target_path)
                        .context("Failed to copy item to additional location")?;
                }
            }

            created_paths.insert(subdir_name.clone(), target_path.clone());
            println!("🪦 Stored '{}' in: {}", item.name, target_path.display());
        }

        // Create symlinks for any remaining enabled subdirs
        self.create_remaining_symlinks(
            &item.name,
            &created_paths,
            created_time,
            modified_time,
            archived_time,
        )?;

        // Save epitaphs if provided - create them in all relevant subdirs following same logic as files
        if let Some(note_text) = note {
            self.save_epitaphs_with_logic(
                &item.name,
                &created_paths,
                note_text,
                &created_time,
                &modified_time,
                &archived_time,
            )?;
        }

        println!(
            "✅ Archived '{}' to {} locations",
            item.name,
            original_subdirs.len()
        );
        if note.is_some() {
            println!("📝 Epitaph saved with the archived item");
        }

        Ok(ArchivedItem {})
    }

    fn get_creation_time(&self, path: &Path) -> Result<DateTime<Utc>> {
        let metadata = fs::metadata(path).context("Failed to get metadata")?;

        if let Ok(created) = metadata.created() {
            Ok(DateTime::from(created))
        } else {
            Ok(DateTime::from(metadata.modified()?))
        }
    }

    fn find_original_subdirs(&self) -> Result<Vec<(String, DateTime<Utc>)>> {
        let mut originals = Vec::new();
        let now = Utc::now();

        if self.config.path_format.created_subdir.is_original() {
            originals.push((
                self.config
                    .path_format
                    .created_subdir
                    .get_name()
                    .unwrap()
                    .to_string(),
                // Use creation time for created subdir - we'll set this properly later
                now,
            ));
        }
        if self.config.path_format.modified_subdir.is_original() {
            originals.push((
                self.config
                    .path_format
                    .modified_subdir
                    .get_name()
                    .unwrap()
                    .to_string(),
                // Use modification time for modified subdir - we'll set this properly later
                now,
            ));
        }
        if self.config.path_format.archived_subdir.is_original() {
            originals.push((
                self.config
                    .path_format
                    .archived_subdir
                    .get_name()
                    .unwrap()
                    .to_string(),
                now, // archived time
            ));
        }

        if originals.is_empty() {
            return Err(anyhow::anyhow!(
                "No subdir configured to store original files"
            ));
        }

        Ok(originals)
    }

    fn create_path_for_subdir(
        &self,
        subdir_name: &str,
        name: &str,
        time: DateTime<Utc>,
    ) -> Result<PathBuf> {
        let date_path = self.config.format_date_path(&time);

        let mut path = self
            .config
            .graveyard
            .join(subdir_name)
            .join(date_path)
            .join(name);

        path = self.ensure_unique_name(path)?;
        Ok(path)
    }

    fn get_path_for_subdir(&self, subdir_name: &str, name: &str, time: DateTime<Utc>) -> PathBuf {
        let date_path = self.config.format_date_path(&time);

        self.config
            .graveyard
            .join(subdir_name)
            .join(date_path)
            .join(name)
    }

    fn create_remaining_symlinks(
        &self,
        name: &str,
        _created_paths: &std::collections::HashMap<String, PathBuf>,
        created_time: DateTime<Utc>,
        modified_time: DateTime<Utc>,
        archived_time: DateTime<Utc>,
    ) -> Result<()> {
        let subdirs = [
            (
                "created",
                &self.config.path_format.created_subdir,
                created_time,
            ),
            (
                "modified",
                &self.config.path_format.modified_subdir,
                modified_time,
            ),
            (
                "archived",
                &self.config.path_format.archived_subdir,
                archived_time,
            ),
        ];

        for (_subdir_type, subdir_config, time) in subdirs {
            if !subdir_config.is_enabled() || subdir_config.is_original() {
                continue; // Skip disabled subdirs and those that already have originals
            }

            let subdir_name = subdir_config.get_name().unwrap();

            if let Some(target_subdir) = subdir_config.get_target() {
                // Always create the path for the immediate target, not resolved chain
                let target_time = if self.config.path_format.created_subdir.get_name()
                    == Some(target_subdir)
                {
                    created_time
                } else if self.config.path_format.modified_subdir.get_name() == Some(target_subdir)
                {
                    modified_time
                } else if self.config.path_format.archived_subdir.get_name() == Some(target_subdir)
                {
                    archived_time
                } else {
                    time
                };

                let target_path = self.get_path_for_subdir(target_subdir, name, target_time);
                let link_path = self.create_path_for_subdir(subdir_name, name, time)?;

                self.ensure_directory_exists(link_path.parent().unwrap())?;
                self.create_symlink(&target_path, &link_path)?;
                println!(
                    "🔗 Created symlink '{}' -> {}",
                    link_path.display(),
                    target_path.display()
                );
            }
        }

        Ok(())
    }

    fn ensure_unique_name(&self, mut path: PathBuf) -> Result<PathBuf> {
        if !path.exists() {
            return Ok(path);
        }

        let original_name = path
            .file_name()
            .context("Invalid path")?
            .to_string_lossy()
            .to_string();

        let mut counter = 1;
        loop {
            let new_name = if let Some(dot_pos) = original_name.rfind('.') {
                format!(
                    "{}_{}{}",
                    &original_name[..dot_pos],
                    counter,
                    &original_name[dot_pos..]
                )
            } else {
                format!("{original_name}_{counter}")
            };

            path.set_file_name(new_name);

            if !path.exists() {
                break;
            }

            counter += 1;
        }

        Ok(path)
    }

    fn save_epitaphs_with_logic(
        &self,
        name: &str,
        created_paths: &std::collections::HashMap<String, PathBuf>,
        note: &str,
        created_time: &DateTime<Utc>,
        modified_time: &DateTime<Utc>,
        archived_time: &DateTime<Utc>,
    ) -> Result<()> {
        // Create epitaph content once
        let epitaph_content = format!(
            "# Epitaph for {}\n\
            # Archived: {}\n\
            # Created: {}\n\
            # Modified: {}\n\
            # Hostname: {}\n\
            \n\
            {}",
            name,
            archived_time.format("%Y-%m-%d %H:%M:%S UTC"),
            created_time.format("%Y-%m-%d %H:%M:%S UTC"),
            modified_time.format("%Y-%m-%d %H:%M:%S UTC"),
            self.config.get_hostname(),
            note
        );

        let epitaph_filename = format!("{name}.epitaph");
        let mut primary_epitaph_path = None;
        let mut created_epitaph_paths = std::collections::HashMap::new();

        // First, create epitaphs for all original file locations
        for (subdir_name, file_path) in created_paths {
            let epitaph_path = file_path.parent().unwrap().join(&epitaph_filename);

            if primary_epitaph_path.is_none() {
                // Write the first epitaph
                fs::write(&epitaph_path, &epitaph_content)
                    .context("Failed to write epitaph file")?;
                primary_epitaph_path = Some(epitaph_path.clone());
                println!("📄 Epitaph written to: {}", epitaph_path.display());
            } else {
                // Copy epitaph to additional original locations
                fs::copy(primary_epitaph_path.as_ref().unwrap(), &epitaph_path)
                    .context("Failed to copy epitaph file")?;
                println!("📄 Epitaph copied to: {}", epitaph_path.display());
            }

            created_epitaph_paths.insert(subdir_name.clone(), epitaph_path);
        }

        // Now create epitaph symlinks for symlink subdirs, following same logic as files
        let subdirs = [
            (
                "created",
                &self.config.path_format.created_subdir,
                *created_time,
            ),
            (
                "modified",
                &self.config.path_format.modified_subdir,
                *modified_time,
            ),
            (
                "archived",
                &self.config.path_format.archived_subdir,
                *archived_time,
            ),
        ];

        for (_subdir_type, subdir_config, time) in subdirs {
            if !subdir_config.is_enabled() || subdir_config.is_original() {
                continue; // Skip disabled subdirs and those that already have originals
            }

            let subdir_name = subdir_config.get_name().unwrap();

            if let Some(target_subdir) = subdir_config.get_target() {
                // Get the target time for path resolution
                let target_time = if self.config.path_format.created_subdir.get_name()
                    == Some(target_subdir)
                {
                    *created_time
                } else if self.config.path_format.modified_subdir.get_name() == Some(target_subdir)
                {
                    *modified_time
                } else if self.config.path_format.archived_subdir.get_name() == Some(target_subdir)
                {
                    *archived_time
                } else {
                    time
                };

                let target_epitaph_path =
                    self.get_path_for_subdir(target_subdir, &epitaph_filename, target_time);
                let link_epitaph_path =
                    self.create_path_for_subdir(subdir_name, &epitaph_filename, time)?;

                self.ensure_directory_exists(link_epitaph_path.parent().unwrap())?;
                self.create_symlink(&target_epitaph_path, &link_epitaph_path)?;
                println!(
                    "🔗 Created epitaph symlink '{}' -> {}",
                    link_epitaph_path.display(),
                    target_epitaph_path.display()
                );
            }
        }

        Ok(())
    }

    fn ensure_directory_exists(&self, path: &Path) -> Result<()> {
        fs::create_dir_all(path).context("Failed to create directory")
    }

    fn create_symlink(&self, target: &Path, link: &Path) -> Result<()> {
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(target, link).context("Failed to create symlink")?;
        }

        #[cfg(windows)]
        {
            if target.is_dir() {
                std::os::windows::fs::symlink_dir(target, link)
                    .context("Failed to create directory symlink")?;
            } else {
                std::os::windows::fs::symlink_file(target, link)
                    .context("Failed to create file symlink")?;
            }
        }

        Ok(())
    }
}

fn copy_dir_all(src: &Path, dst: &Path) -> Result<()> {
    fs::create_dir_all(dst)?;
    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let ty = entry.file_type()?;
        if ty.is_dir() {
            copy_dir_all(&entry.path(), &dst.join(entry.file_name()))?;
        } else {
            fs::copy(entry.path(), dst.join(entry.file_name()))?;
        }
    }
    Ok(())
}