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
//
// Wildland Project
//
// Copyright © 2023 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 anyhow::Context as _;
use clap::{Arg, ArgAction, ArgMatches, Command};
use reedline_repl_rs::Repl;
use s_macro::s;
use wildland_corex::api::{SpecialFileOperations, SpecialFileType};

use crate::{match_context, Context};

#[tracing::instrument(level = "trace", err(Debug), skip(_args, context))]
fn h_sfo_init(_args: ArgMatches, context: &mut Context) -> anyhow::Result<Option<String>> {
    match_context!(context, cargo => None, sfo => None)?;
    context.init_sfo("./sfo")?;
    Ok(Some(s!(
        "Special File Operations Service initialised with an empty registry"
    )))
}

#[tracing::instrument(level = "trace", err(Debug), skip(args, context))]
fn h_sfo_create_special_file(
    args: ArgMatches,
    context: &mut Context,
) -> anyhow::Result<Option<String>> {
    match_context!(context, sfo => Some(_))?;

    let file_name: String = args
        .get_one::<String>("file_name")
        .context("file name not provided")?
        .to_owned();

    let file_type: SpecialFileType = args
        .get_one::<String>("file_type")
        .context("file type not provided")?
        .to_owned()
        .try_into()?;

    let input_stream = None;

    context.sfo.as_mut().unwrap().create_special_file(
        file_name.to_owned(),
        file_type,
        input_stream,
    )?;
    Ok(Some(s!("Special File created: {}", file_name)))
}

#[tracing::instrument(level = "trace", err(Debug), skip(args, context))]
fn h_sfo_remove_special_file(
    args: ArgMatches,
    context: &mut Context,
) -> anyhow::Result<Option<String>> {
    match_context!(context, sfo => Some(_))?;

    let file_name: String = args
        .get_one::<String>("file_name")
        .context("file name not provided")?
        .to_owned();

    let file_type: SpecialFileType = args
        .get_one::<String>("file_type")
        .context("file type not provided")?
        .to_owned()
        .try_into()?;

    context
        .sfo
        .as_mut()
        .unwrap()
        .remove_special_file(file_name.to_owned(), file_type.to_owned())?;
    Ok(Some(s!(
        "Special File ({:?}) removed: {}",
        file_type,
        file_name
    )))
}

#[tracing::instrument(level = "trace", err(Debug), skip(context))]
fn h_sfo_get_special_file_path(
    args: ArgMatches,
    context: &mut Context,
) -> anyhow::Result<Option<String>> {
    match_context!(context, sfo => Some(_))?;

    let file_name: String = args
        .get_one::<String>("file_name")
        .context("file name not provided")?
        .to_owned();

    let file_type: SpecialFileType = args
        .get_one::<String>("file_type")
        .context("file type not provided")?
        .to_owned()
        .try_into()?;

    let file_path = context
        .sfo
        .as_ref()
        .unwrap()
        .get_special_file_path(file_name, file_type)?;

    Ok(Some(s!("Special file registry\n {:?}", file_path)))
}

#[tracing::instrument(level = "trace", err(Debug), skip(args, context))]
fn h_sfo_read_from_special_file(
    args: ArgMatches,
    context: &mut Context,
) -> anyhow::Result<Option<String>> {
    match_context!(context, sfo => Some(_))?;

    let file_name: String = args
        .get_one::<String>("file_name")
        .context("file name not provided")?
        .to_owned();

    let file_type: SpecialFileType = args
        .get_one::<String>("file_type")
        .context("file type not provided")?
        .to_owned()
        .try_into()?;

    let contents = context
        .sfo
        .as_mut()
        .unwrap()
        .read_from_special_file(file_name, file_type)?;

    if args
        .get_one::<bool>("interpret as ascii")
        .unwrap()
        .to_owned()
    {
        Ok(Some(s!(
            "Special File contents: {}",
            String::from_utf8(contents)?
        )))
    } else {
        Ok(Some(s!("Special File contents: {:?}", contents)))
    }
}

#[tracing::instrument(level = "trace", err(Debug), skip(args, context))]
fn h_sfo_write_to_special_file(
    args: ArgMatches,
    context: &mut Context,
) -> anyhow::Result<Option<String>> {
    match_context!(context, sfo => Some(_))?;

    let file_name: String = args
        .get_one::<String>("file_name")
        .context("file name not provided")?
        .to_owned();

    let file_type: SpecialFileType = args
        .get_one::<String>("file_type")
        .context("file type not provided")?
        .to_owned()
        .try_into()?;

    let truncate = args.get_one::<bool>("append").unwrap().to_owned();

    let new_contents = args
        .get_one::<String>("input")
        .context("input not provided")?
        .to_owned();

    context.sfo.as_mut().unwrap().write_to_special_file(
        file_name.to_owned(),
        file_type,
        new_contents.into_bytes(),
        truncate,
    )?;
    Ok(Some(s!("Data written to file: {}", file_name)))
}

pub fn extend(repl: Repl<Context, anyhow::Error>) -> Repl<Context, anyhow::Error> {
    repl.with_command(
        Command::new("sfo-init").about("Initialise SfoService"),
        h_sfo_init,
    )
    .with_command(
        Command::new("sfo-create")
            .about("Create a new special file")
            .arg(Arg::new("file_name").required(true))
            .arg(Arg::new("file_type").required(true)),
        h_sfo_create_special_file,
    )
    .with_command(
        Command::new("sfo-remove")
            .about("Remove a special file")
            .arg(Arg::new("file_name").required(true))
            .arg(Arg::new("file_type").required(true)),
        h_sfo_remove_special_file,
    )
    .with_command(
        Command::new("sfo-get-path")
            .arg(Arg::new("file_name").required(true))
            .arg(Arg::new("file_type").required(true))
            .about("Get the path of a special file"),
        h_sfo_get_special_file_path,
    )
    .with_command(
        Command::new("sfo-read")
            .about("Read a special file contents")
            .arg(Arg::new("file_name").required(true))
            .arg(Arg::new("file_type").required(true))
            .arg(
                Arg::new("interpret as ascii")
                    .action(ArgAction::SetTrue)
                    .short('a')
                    .long("ascii"),
            ),
        h_sfo_read_from_special_file,
    )
    .with_command(
        Command::new("sfo-write")
            .about("Write to a special file")
            .arg(Arg::new("file_name").required(true))
            .arg(Arg::new("file_type").required(true))
            .arg(Arg::new("input").required(true))
            .arg(
                Arg::new("append")
                    .action(ArgAction::SetTrue)
                    .short('a')
                    .long("append"),
            ),
        h_sfo_write_to_special_file,
    )
}