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
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use eyre::Result;
use floppy_disk::prelude::*;
use tokio::io::AsyncWriteExt;
use tracing::{debug, error, warn};

pub struct DiskDrive<
    'a,
    'b,
    F1: FloppyDisk<'a> + FloppyDiskUnixExt + Send + Sync + 'a,
    F2: FloppyDisk<'b> + FloppyDiskUnixExt + Send + Sync + 'b,
> where
    <F1 as FloppyDisk<'a>>::Permissions: FloppyUnixPermissions,
    <F1 as FloppyDisk<'a>>::Metadata: FloppyUnixMetadata,

    <F1 as FloppyDisk<'a>>::DirBuilder: Send,
    <F1 as FloppyDisk<'a>>::DirEntry: Send,
    <F1 as FloppyDisk<'a>>::File: Send,
    <F1 as FloppyDisk<'a>>::FileType: Send,
    <F1 as FloppyDisk<'a>>::Metadata: Send,
    <F1 as FloppyDisk<'a>>::OpenOptions: Send,
    <F1 as FloppyDisk<'a>>::Permissions: Send,
    <F1 as FloppyDisk<'a>>::ReadDir: Send,

    <F2 as FloppyDisk<'b>>::Permissions: FloppyUnixPermissions,
    <F2 as FloppyDisk<'b>>::Metadata: FloppyUnixMetadata,

    <F2 as FloppyDisk<'b>>::DirBuilder: Send,
    <F2 as FloppyDisk<'b>>::DirEntry: Send,
    <F2 as FloppyDisk<'b>>::File: Send,
    <F2 as FloppyDisk<'b>>::FileType: Send,
    <F2 as FloppyDisk<'b>>::Metadata: Send,
    <F2 as FloppyDisk<'b>>::OpenOptions: Send,
    <F2 as FloppyDisk<'b>>::Permissions: Send,
    <F2 as FloppyDisk<'b>>::ReadDir: Send,
{
    _f1: std::marker::PhantomData<&'a F1>,
    _f2: std::marker::PhantomData<&'b F2>,
}

impl<
        'a,
        'b,
        F1: FloppyDisk<'a> + FloppyDiskUnixExt + Send + Sync + 'a,
        F2: FloppyDisk<'b> + FloppyDiskUnixExt + Send + Sync + 'b,
    > DiskDrive<'a, 'b, F1, F2>
where
    <F1 as FloppyDisk<'a>>::Permissions: FloppyUnixPermissions,
    <F1 as FloppyDisk<'a>>::Metadata: FloppyUnixMetadata,
    <F2 as FloppyDisk<'b>>::Permissions: FloppyUnixPermissions,
    <F2 as FloppyDisk<'b>>::Metadata: FloppyUnixMetadata,
{
    pub async fn copy_between(src: &'a F1, dest: &'b F2) -> Result<()> {
        Self::do_copy(src, dest, None, None).await
    }

    pub async fn copy_from_src<P: Into<PathBuf>>(
        src: &'a F1,
        dest: &'b F2,
        src_scope: P,
    ) -> Result<()> {
        let src_scope = src_scope.into();
        Self::do_copy(src, dest, Some(src_scope), None).await
    }

    pub async fn copy_to_dest<P: Into<PathBuf>>(
        src: &'a F1,
        dest: &'b F2,
        dest_scope: P,
    ) -> Result<()> {
        let dest_scope = dest_scope.into();
        Self::do_copy(src, dest, None, Some(dest_scope)).await
    }

    async fn do_copy(
        src: &'a F1,
        dest: &'b F2,
        src_path: Option<PathBuf>,
        dest_path: Option<PathBuf>,
    ) -> Result<()> {
        let src_path = src_path.unwrap_or_else(|| PathBuf::from("/"));
        let dest_path = dest_path.unwrap_or_else(|| PathBuf::from("/"));
        let paths = if src.metadata(&src_path).await?.is_file() {
            debug!("copying src file {}", src_path.display());
            let mut out = BTreeSet::new();
            out.insert(src_path);
            out
        } else {
            debug!("copying src dir {}", src_path.display());
            nyoom::walk_ordered(src, src_path).await?
        };
        for src_path in paths {
            debug!("copy {} -> {}", src_path.display(), dest_path.display());
            let metadata = <F1 as FloppyDisk<'a>>::metadata(src, &src_path).await?;
            let file_type = metadata.file_type();
            if file_type.is_dir() {
                Self::copy_dir_to_memfs(src, dest, &src_path, &dest_path).await?;
            } else if file_type.is_file() {
                Self::copy_file_to_memfs(src, dest, &src_path, &dest_path).await?;
            } else if file_type.is_symlink() {
                Self::add_symlink_to_memfs(src, dest, &src_path, &dest_path).await?;
            } else {
                error!("unknown file type for source path {src_path:?}");
            }
        }

        Ok(())
    }

    async fn copy_file_to_memfs(
        src: &'a F1,
        dest: &'b F2,
        src_path: &Path,
        dest_path: &Path,
    ) -> Result<()> {
        debug!("creating file {dest_path:?}");
        if let Some(memfs_parent) = dest_path.parent() {
            dest.create_dir_all(memfs_parent).await?;
        }

        let mut src_handle: <F1 as FloppyDisk>::File = <F1::OpenOptions>::new()
            .read(true)
            .open(src, src_path)
            .await?;
        {
            let dest_metadata = <F2 as FloppyDisk>::metadata(dest, dest_path).await;
            let dest_handle = <F2::OpenOptions>::new();
            let dest_handle = dest_handle.create(true).write(true);

            // if dest metadata doesn't exist, just copy directly
            if dest_metadata.is_err() {
                debug!("dest {dest_path:?} doesn't exist, copying directly!");
                let mut dest_handle: <F2 as FloppyDisk>::File =
                    dest_handle.open(dest, dest_path).await?;

                tokio::io::copy(&mut src_handle, &mut dest_handle).await?;
                return Ok(());
            }

            // if dest exists and is a dir, copy into it
            let dest_metadata = dest_metadata?;
            if dest_metadata.is_dir() {
                debug!("copying into dir {dest_path:?}");
                let dest_path = dest_path.join(Path::new(src_path.file_name().unwrap()));
                debug!("target path = {dest_path:?}");
                let mut dest_handle: <F2 as FloppyDisk>::File =
                    dest_handle.open(dest, &dest_path).await?;

                let written = tokio::io::copy(&mut src_handle, &mut dest_handle).await?;
                debug!("wrote {written} bytes");
                dest_handle.flush().await?;

                // copy permissions
                let src_metadata = src_handle.metadata().await?;
                let src_permissions = src_metadata.permissions();
                let mode = <<F1 as FloppyDisk<'_>>::Permissions as FloppyUnixPermissions>::mode(
                    &src_permissions,
                );

                let permissions = <<F2 as FloppyDisk>::Permissions>::from_mode(mode);
                let uid = src_metadata.uid()?;
                let gid = src_metadata.gid()?;

                <F2 as FloppyDiskUnixExt>::chown(dest, &dest_path, uid, gid).await?;
                <F2 as FloppyDisk>::set_permissions(dest, &dest_path, permissions).await?;

                return Ok(());
            }

            // if dest exists and is a file, copy into it
            if dest_metadata.is_file() {
                warn!("overwriting dest file {dest_path:?}");
                let mut dest_handle: <F2 as FloppyDisk>::File =
                    dest_handle.open(dest, dest_path).await?;

                tokio::io::copy(&mut src_handle, &mut dest_handle).await?;
                return Ok(());
            }

            // if dest exists and is a symlink, log error and return
            if dest_metadata.is_symlink() {
                warn!("dest path {dest_path:?} is a symlink, skipping copy!");
                return Ok(());
            }
        }

        let src_metadata = src_handle.metadata().await?;
        let src_permissions = src_metadata.permissions();
        let mode =
            <<F1 as FloppyDisk<'_>>::Permissions as FloppyUnixPermissions>::mode(&src_permissions);
        let permissions = <<F2 as FloppyDisk>::Permissions>::from_mode(mode);
        let uid = src_metadata.uid()?;
        let gid = src_metadata.gid()?;
        <F2 as FloppyDiskUnixExt>::chown(dest, dest_path, uid, gid).await?;
        <F2 as FloppyDisk>::set_permissions(dest, dest_path, permissions).await?;

        Ok(())
    }

    async fn copy_dir_to_memfs(
        src: &'a F1,
        dest: &'b F2,
        src_path: &Path,
        dest_path: &Path,
    ) -> Result<()> {
        dest.create_dir_all(dest_path).await?;

        let src_metadata = src.metadata(src_path).await?;
        let mode = src_metadata.permissions().mode();
        let permissions = <F2 as FloppyDisk>::Permissions::from_mode(mode);
        dest.set_permissions(dest_path, permissions).await?;
        dest.chown(dest_path, src_metadata.uid()?, src_metadata.gid()?)
            .await?;

        Ok(())
    }

    async fn add_symlink_to_memfs(
        src: &F1,
        dest: &F2,
        path: &Path,
        memfs_path: &Path,
    ) -> Result<()> {
        let link = src.read_link(path).await?;
        debug!("linking {memfs_path:?} to {link:?}");
        dest.symlink(link, memfs_path.into()).await?;

        Ok(())
    }
}