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
use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::ops::Deref;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use anyhow::{anyhow, Result};
use log::{error, info, trace};
use crate::analyze::analysis::{AnalysisFile, ResultEntryRef};
use crate::analyze::worker::{AnalysisJob, AnalysisResult, MarkedIntermediaryFile, WorkerArgument};
use crate::data::{GeneralHash, SaveFile, SaveFileEntry, SaveFileEntryType};
use crate::threadpool::ThreadPool;

pub struct AnalysisSettings {
    pub input: PathBuf,
    pub output: PathBuf,
    pub threads: Option<usize>,
}

pub fn run(analysis_settings: AnalysisSettings) -> Result<()> {
    let mut input_file_options = fs::File::options();
    input_file_options.read(true);
    input_file_options.write(false);

    let mut output_file_options = fs::File::options();
    output_file_options.create(true);
    output_file_options.write(true);
    output_file_options.truncate(true);

    let input_file = match input_file_options.open(analysis_settings.input) {
        Ok(file) => file,
        Err(err) => {
            return Err(anyhow!("Failed to open input file: {}", err));
        }
    };

    let output_file = match output_file_options.open(analysis_settings.output) {
        Ok(file) => file,
        Err(err) => {
            return Err(anyhow!("Failed to open output file: {}", err));
        }
    };

    let mut input_buf_reader = std::io::BufReader::new(&input_file);
    let mut output_buf_writer = std::io::BufWriter::new(&output_file);

    let mut save_file = SaveFile::new(&mut output_buf_writer, &mut input_buf_reader, true, true, true);
    save_file.load_header()?;

    save_file.load_all_entries_no_filter()?;
    
    let mut file_by_path = save_file.file_by_path;
    let mut file_by_path_marked = HashMap::with_capacity(file_by_path.len());
    let mut file_by_hash = save_file.file_by_hash;
    let mut all_files = save_file.all_entries;
    
    for (path, entry) in file_by_path.iter_mut() {
        file_by_path_marked.insert(path.clone(), MarkedIntermediaryFile {
            saved_file_entry: Arc::clone(entry),
            file: Arc::new(Mutex::new(None)),
        });
    }
    drop(file_by_path);
    
    // delete all entries with no collision
    
    file_by_hash.retain(|_, entry| {
        entry.len() >= 2
    });
    file_by_hash.shrink_to_fit();
    
    // delete all entries with no collision
    
    all_files.retain(|entry| {
        Arc::strong_count(entry) >= 3 // All_entries*1 + file_by_path_marked*1 + file_by_hash*1
    });
    
    let file_by_path = Arc::new(file_by_path_marked);

    // create thread pool

    let mut args = Vec::with_capacity(analysis_settings.threads.unwrap_or_else(|| num_cpus::get()));
    for _ in 0..args.capacity() {
        args.push(WorkerArgument {
            file_by_path: Arc::clone(&file_by_path)
        });
    }

    let pool: ThreadPool<AnalysisJob, AnalysisResult> = ThreadPool::new(args, crate::cmd::analyze::worker::worker_run);
    
    for entry in &all_files {
        pool.publish(AnalysisJob::new(Arc::clone(entry)));
    }
    
    loop {
        match pool.receive_timeout(Duration::from_secs(10)) {
            Ok(result) => {
                info!("Result: {:?}", result);
            }
            Err(_) => {
                break;
            }
        }
    }

    drop(pool);
    
    let mut duplicated_bytes: u64 = 0;

    for entry in &all_files {
        trace!("File: {}", entry.path);
        let file = file_by_path.get(&entry.path).unwrap();
        let file = file.file.lock().unwrap();
        if let Some(file) = file.deref() {
            let parent = file.parent().lock().unwrap();
            match parent.deref() {
                Some(parent) => {
                    // check if parent is also conflicting

                    let parent = parent.upgrade().unwrap();
                    let parent_hash;
                    match parent.deref() {
                        AnalysisFile::File(info) => {
                            parent_hash = Some(&info.content_hash);
                        },
                        AnalysisFile::Directory(info) => {
                            parent_hash = Some(&info.content_hash);
                        },
                        AnalysisFile::Symlink(info) => {
                            parent_hash = Some(&info.content_hash);
                        },
                        AnalysisFile::Other(_) => {
                            parent_hash = None;
                        },
                    }

                    let parent_conflicting;

                    match parent_hash {
                        None => {parent_conflicting = false;}
                        Some(parent_hash) => {
                            parent_conflicting = match file_by_hash.get(parent_hash) {
                                Some(entries) => {
                                    entries.len() >= 2
                                },
                                None => {
                                    false
                                }
                            }
                        }
                    }

                    if !parent_conflicting {
                        duplicated_bytes += write_result_entry(file, &file_by_hash, &mut output_buf_writer);
                    }
                }
                None => {
                    duplicated_bytes += write_result_entry(file, &file_by_hash, &mut output_buf_writer);
                }
            }
        } else {
            error!("File not analyzed yet: {:?}", entry.path);
        }
    }

    output_buf_writer.flush().expect("Unable to flush file");
    
    print!("There are {} GB of duplicated files", duplicated_bytes / 1024 / 1024 / 1024);

    Ok(())
}

#[derive(Debug, PartialEq, Hash, Eq)]
struct SetKey<'a> {
    size: u64,
    ftype: &'a SaveFileEntryType,
}
fn write_result_entry(file: &AnalysisFile, file_by_hash: &HashMap<GeneralHash, Vec<Arc<SaveFileEntry>>>, output_buf_writer: &mut std::io::BufWriter<&fs::File>) -> u64 {
    let hash = match file {
        AnalysisFile::File(info) => &info.content_hash,
        AnalysisFile::Directory(info) => &info.content_hash,
        AnalysisFile::Symlink(info) => &info.content_hash,
        AnalysisFile::Other(_) => {
            return 0;
        }
    };
    
    let mut sets: HashMap<SetKey, Vec<&SaveFileEntry>> = HashMap::new();

    for file in file_by_hash.get(hash).unwrap() {
        sets.entry(SetKey {
            size: file.size,
            ftype: &file.file_type
        }).or_insert(Vec::new()).push(file);
    }
    
    let mut result_size: u64 = 0;
    
    for set in &sets {
        if set.1.len() <= 1 {
            continue;
        }
        
        if &set.1[0].path != file.path() {
            // no duplicates
            continue;
        }
        
        let mut conflicting = Vec::with_capacity(set.1.len());
        for file in set.1 {
            conflicting.push(&file.path);
        }
        
        let result = ResultEntryRef {
            ftype: &set.0.ftype,
            size: set.0.size,
            hash,
            conflicting,
        };
        output_buf_writer.write(serde_json::to_string(&result).unwrap().as_bytes()).expect("Unable to write to file");
        output_buf_writer.write('\n'.to_string().as_bytes()).expect("Unable to write to file");

        result_size += result.size * (result.conflicting.len() as u64 - 1);
    }
    
    return result_size;
}

mod worker;
pub mod analysis;