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
//
// Wildland Project
//
// Copyright © 2022 Golem Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use std::path::{Component, PathBuf};

use anyhow::{anyhow, Context as _};
use reedline_repl_rs::clap::ArgMatches;
use s_macro::s;
pub use wildland_cargo_lib::api::CargoLib;
use wildland_corex::dfs::interface::node_stat::NodeType;
use wildland_corex::dfs::interface::{
    AbortFlag,
    DfsFrontendError,
    DummyIStream,
    DummyProgressReporter,
};

use crate::plugins::dfs::stream::{DevShellIStream, DevShellOStream, DevShellProgressReporter};
use crate::sigint::Ctrlc;
use crate::Context;

/*
   ===========================
   Handler Auxiliaries
   ===========================
*/

// ##############################################
// generic solver auxiliaries
// ##############################################

#[tracing::instrument(level = "trace", ret, err(Debug))]
pub fn aux_resolve_path(path: &String, cwd: PathBuf) -> anyhow::Result<String> {
    tracing::trace!("working with {}", path);
    let path = PathBuf::from(path);

    let mut components = path.components().peekable();
    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
        components.next();
        PathBuf::from(c.as_os_str())
    } else {
        PathBuf::new()
    };
    if path.is_relative() {
        ret = cwd.join(ret);
    }

    for component in components {
        match component {
            Component::Prefix(..) => unreachable!(),
            Component::RootDir => {
                ret.push(component.as_os_str());
            }
            Component::CurDir => {}
            Component::ParentDir => {
                ret.pop();
            }
            Component::Normal(c) => {
                ret.push(c);
            }
        }
    }
    Ok(ret.to_str().context("Failed to serialize path")?.to_owned())
}

#[tracing::instrument(level = "trace", err(Debug), ret, skip(ctx))]
pub fn aux_dfs_get_path_type(ctx: &mut Context, path: &String) -> anyhow::Result<NodeType> {
    let path = aux_resolve_path(path, ctx.current_path.clone())?;
    let dfsapi = ctx.get_dfs().context("can't get dfs api")?;
    let node = dfsapi
        .metadata(path.clone())
        .context(s!("path does not exist: {}", path))?;
    Ok(node.node_type)
}

// ##############################################
// morphing and display
// ##############################################

#[tracing::instrument(level = "trace", ret, err(Debug))]
pub fn aux_size_mod(size: usize) -> anyhow::Result<String> {
    let mut size = size;
    let mut modifier = " b";
    if size > 1024 {
        size /= 1024;
        modifier = " Kib";
    }
    if size > 1024 {
        size /= 1024;
        modifier = " Mib";
    }
    if size > 1024 {
        size /= 1024;
        modifier = " Gib";
    }
    if size > 1024 {
        size /= 1024;
        modifier = " Tib";
    }
    Ok(format!("{size}{modifier}"))
}

// ##############################################
// local path solver
// ##############################################

#[tracing::instrument(level = "trace", ret, err(Debug))]
pub fn aux_resolve_local(path: &String, cwd: PathBuf) -> anyhow::Result<String> {
    let homedir = std::env::var("HOME").context("can not find HOME environment variable")?;

    // we do not keep cwd on local side
    let cwd = PathBuf::from("/");

    if path.matches('~').count() > 1 {
        return Err(anyhow!("`~` can only be used only once"));
    }
    if path.starts_with("~/") {
        let mut path = path.clone();
        path.replace_range(0..1, &homedir);
        aux_resolve_path(&path, cwd)
    } else if path.contains('~') {
        Err(anyhow!("`~` can only be used at the beginning of the path"))
    } else {
        aux_resolve_path(path, cwd)
    }
}

/*
   ===========================
   handler implementations
   ===========================
*/

// ##############################################
// constructive operations
// ##############################################

#[tracing::instrument(level = "trace", err(Debug), skip(args, ctx))]
pub(crate) fn h_touch(args: ArgMatches, ctx: &mut Context) -> anyhow::Result<Option<String>> {
    let path = args
        .get_one::<String>("path")
        .context("path not provided")?;
    let path = aux_resolve_path(path, ctx.current_path.clone())?;
    let dfsapi = ctx.get_dfs().context("can't get dfs api")?;

    dfsapi
        .upload(
            path.clone(),
            DummyIStream::boxed(vec![]),
            Box::new(DummyProgressReporter {}),
            &AbortFlag::new(),
            None,
        )
        .context("Failed to create file")?;
    Ok(Some(s!("Ok: File Created: {}", path)))
}

#[tracing::instrument(level = "trace", err(Debug), skip(args, ctx))]
pub(crate) fn h_mkdir(args: ArgMatches, ctx: &mut Context) -> anyhow::Result<Option<String>> {
    let path = args
        .get_one::<String>("path")
        .context("path not provided")?;
    let path = aux_resolve_path(path, ctx.current_path.clone())?;
    // let path = PathBuf::from(path).file_name().unwrap().to_str().unwrap().to_owned();
    tracing::debug!("creating dir with path {path}");
    let dfsapi = ctx.get_dfs().context("can't get dfs api")?;

    dfsapi.create_dir(path).context("Failed to create file")?;
    Ok(Some(s!("Ok: Directory Created")))
}

// ##############################################
// destructive file operations
// ##############################################

#[tracing::instrument(level = "trace", err(Debug), skip(args, ctx))]
pub(crate) fn h_rmdir(args: ArgMatches, ctx: &mut Context) -> anyhow::Result<Option<String>> {
    let path = args
        .get_one::<String>("path")
        .context("path not provided")?;
    let is_recursive = args
        .get_one::<bool>("recursive")
        .unwrap_or(&false)
        .to_owned();

    let path = aux_resolve_path(path, ctx.current_path.clone())?;
    let dfsapi = ctx.get_dfs().context("can't get dfs api")?;
    dfsapi
        .remove_dir(path, is_recursive)
        .context("Failed to remove directory")?;
    Ok(Some(s!("Ok: Directory Removed")))
}

#[tracing::instrument(level = "trace", err(Debug), skip(args, ctx))]
pub(crate) fn h_rm(args: ArgMatches, ctx: &mut Context) -> anyhow::Result<Option<String>> {
    let path = args
        .get_one::<String>("path")
        .context("path not provided")?;
    let path = aux_resolve_path(path, ctx.current_path.clone())?;

    let dfsapi = ctx.get_dfs().context("can't get dfs api")?;
    dfsapi.remove_file(path)?;
    Ok(Some(s!("Ok: File Removed")))
}

#[tracing::instrument(level = "trace", err(Debug), skip(args, ctx))]
pub(crate) fn h_stat(args: ArgMatches, ctx: &mut Context) -> anyhow::Result<Option<String>> {
    let path = args
        .get_one::<String>("path")
        .context("path not provided")?;
    let path = aux_resolve_path(path, ctx.current_path.clone())?;

    let dfsapi = ctx.get_dfs().context("can't get dfs api")?;
    let meta = dfsapi.metadata(path.clone())?;
    println!(
        "file:\t{},\nuuid:\t{}\nsize\t{}\n",
        path, meta.wildland_object_id, meta.size
    );
    Ok(Some(s!("Ok: File statistics printed")))
}

// ##############################################
// navigation
// ##############################################

#[tracing::instrument(level = "trace", err(Debug), skip(args, ctx))]
pub(crate) fn h_cd(args: ArgMatches, ctx: &mut Context) -> anyhow::Result<Option<String>> {
    let path = args
        .get_one::<String>("path")
        .context("path not provided")?;

    let path = aux_resolve_path(path, ctx.current_path.clone())?;
    if aux_dfs_get_path_type(ctx, &path)? != NodeType::Dir {
        return Err(anyhow::anyhow!("path is not a directory"));
    }
    ctx.current_path = std::path::PathBuf::from(path);
    Ok(Some(s!("")))
}

#[tracing::instrument(level = "trace", err(Debug), skip(args, ctx))]
pub(crate) fn h_ls(args: ArgMatches, ctx: &mut Context) -> anyhow::Result<Option<String>> {
    let path = match args.get_one::<String>("path") {
        Some(p) => p.to_owned(),
        None => ctx.current_path.clone().to_string_lossy().into(),
    };
    let path = aux_resolve_path(&path, ctx.current_path.clone())?;

    let dfs_api = ctx.get_dfs().context("can't get dfs api")?;
    let entries = dfs_api.read_dir(path).context("Failed to read directory")?;
    for entry in entries {
        let meta = entry.stat;
        let size = aux_size_mod(meta.size).unwrap_or(s!("???"));
        let modifier = match meta.node_type {
            NodeType::File => "-",
            NodeType::Dir => "d",
            NodeType::Other => "?",
            NodeType::Symlink => "l",
        };
        let perms = match meta.permissions.is_readonly() {
            true => "r-",
            false => "rw",
        };
        let name = PathBuf::from(entry.item_name)
            .file_name()
            .unwrap()
            .to_str()
            .unwrap()
            .to_owned();
        println!(" {modifier} {perms} \t{size: <9}\t{name}");
    }
    Ok(Some(s!("Ok: Directory listed")))
}

#[tracing::instrument(level = "trace", err(Debug), skip(args, ctx))]
pub(crate) fn h_get_path(args: ArgMatches, ctx: &mut Context) -> anyhow::Result<Option<String>> {
    let uuid = args
        .get_one::<String>("uuid")
        .context("uuid not provided")?;

    let dfs_api = ctx.get_dfs().context("can't get dfs api")?;
    let entries = dfs_api.get_path(uuid.to_owned())?;
    println!("entries: {:?}", entries);
    Ok(Some(s!("Ok: uuid processed, paths printed")))
}

#[tracing::instrument(level = "trace", err(Debug), skip(_args, ctx))]
pub(crate) fn h_pwd(_args: ArgMatches, ctx: &mut Context) -> anyhow::Result<Option<String>> {
    Ok(Some(s!(ctx
        .current_path
        .clone()
        .into_os_string()
        .into_string()
        .map_err(|_| anyhow!(
            "could not transform path to string"
        ))?)))
}

// ##############################################
// morphing operations
// ##############################################

#[tracing::instrument(level = "trace", err(Debug), skip(args, ctx))]
pub(crate) fn h_rename(args: ArgMatches, ctx: &mut Context) -> anyhow::Result<Option<String>> {
    let lpath = args
        .get_one::<String>("source_path")
        .context("source path not provided")?;
    let lpath = aux_resolve_path(lpath, ctx.current_path.clone())?;

    let rpath = args
        .get_one::<String>("target_path")
        .context("target path not provided")?;
    let rpath = aux_resolve_path(rpath, ctx.current_path.clone())?;

    let dfsapi = ctx.get_dfs().context("can't get dfs api")?;
    dfsapi
        .rename(lpath, rpath)
        .context("Failed to rename directory")?;
    Ok(Some(s!("Ok: Directory renamed")))
}

// ##############################################
// netlink operations
//   related to the network
//   interface, but not only
// ##############################################

#[tracing::instrument(level = "trace", err(Debug), skip(args, ctx))]
pub(crate) fn h_get(args: ArgMatches, ctx: &mut Context) -> anyhow::Result<Option<String>> {
    let source_path = args
        .get_one::<String>("source_path")
        .context("path not provided")?;
    let source_path = aux_resolve_path(source_path, ctx.current_path.clone())?;

    let target_path = args
        .get_one::<String>("target_path")
        .context("remote path not provided")?;

    let dfs_api = ctx.get_dfs().context("can't get dfs api")?;
    let ostream = Box::new(DevShellOStream::try_new(target_path)?);

    let abort_flag = AbortFlag::new();
    let _ctrlc = Ctrlc::new({
        let flag = abort_flag.clone();
        move || flag.set()
    });

    match dfs_api.download(
        source_path.clone(),
        ostream,
        Box::new(DevShellProgressReporter {}),
        &abort_flag,
    ) {
        Ok(_) => Ok(Some(format!(
            "File {source_path} downloaded to {target_path}"
        ))),
        Err(DfsFrontendError::Aborted) => Ok(Some("Downloading canceled".into())),
        Err(e) => Err(e.into()),
    }
}

#[tracing::instrument(level = "trace", err(Debug), skip(args, ctx))]
pub(crate) fn h_put(args: ArgMatches, ctx: &mut Context) -> anyhow::Result<Option<String>> {
    // resolve source_path
    let source_path = args
        .get_one::<String>("source_path")
        .context("local path not provided")?;

    // resolve target_path
    let target_path = args
        .get_one::<String>("target_path")
        .context("remote path not provided")?;
    let target_path = aux_resolve_path(target_path, ctx.current_path.clone())?;

    if !PathBuf::from(source_path.clone()).exists() {
        return Err(anyhow::anyhow!("local path does not exist: {source_path}"));
    }

    let dfs_api = ctx.get_dfs().context("can't get dfs api")?;
    let istream = Box::new(DevShellIStream::try_new(source_path)?);

    let abort_flag = AbortFlag::new();
    let _ctrlc = Ctrlc::new({
        let flag = abort_flag.clone();
        move || flag.set()
    });

    match dfs_api.upload(
        target_path.clone(),
        istream,
        Box::new(DevShellProgressReporter {}),
        &abort_flag,
        None,
    ) {
        Ok(_) => Ok(Some(format!(
            "File {source_path} uploaded as {target_path}"
        ))),
        Err(DfsFrontendError::Aborted) => Ok(Some("Uploading canceled".into())),
        Err(e) => Err(e.into()),
    }
}