1
use clap::{Parser, Subcommand};
2
use cli_core::{CliListDataFindings, CliSelectColumn, CommandError, start_server};
3
use rpc::{ScriptCtx, Session};
4
use server::bootstrap::ADMIN_USER_ID;
5
use server::command::Argument;
6
use sqlx::types::Uuid;
7
use std::collections::HashMap;
8
use std::str::FromStr;
9
use tracing::level_filters::LevelFilter;
10

            
11
mod account_merge;
12
mod dispatch;
13
mod disposable;
14
mod eval;
15
mod flat;
16
mod references;
17
mod reports;
18
mod script;
19
mod ssh_key;
20
mod template;
21
mod transaction;
22

            
23
use dispatch::run_and_print;
24
use eval::{RenderMode, build_remove_ssh_key_form, escape_str, eval_print};
25
use flat::{AccountForms, CommodityForms, ConfigForms, TagForms, delete_tag_confirmed};
26
use reports::ReportsCmd;
27
use script::ScriptCmd;
28
use std::io::IsTerminal;
29
use template::TemplateCmd;
30
use transaction::TransactionCmd;
31

            
32
#[derive(Debug, Clone)]
33
struct FieldContentPair {
34
    field: String,
35
    content: String,
36
}
37

            
38
impl FromStr for FieldContentPair {
39
    type Err = String;
40

            
41
3
    fn from_str(s: &str) -> Result<Self, Self::Err> {
42
3
        let parts: Vec<&str> = s.splitn(2, '=').collect();
43
3
        if parts.len() == 2 {
44
2
            Ok(FieldContentPair {
45
2
                field: parts[0].to_string(),
46
2
                content: parts[1].to_string(),
47
2
            })
48
        } else {
49
1
            Err("Expected format `field=content`".to_string())
50
        }
51
3
    }
52
}
53

            
54
#[derive(Parser, Debug)]
55
#[command(name = "nomisync", about = "Nomisync automation CLI")]
56
struct Cli {
57
    #[arg(short = 'u', long)]
58
    userid: Uuid,
59

            
60
    #[arg(short = 'd', long)]
61
    database: Option<String>,
62

            
63
    #[arg(long)]
64
    setopt: Option<FieldContentPair>,
65

            
66
    #[arg(long)]
67
    loglevel: Option<LevelFilter>,
68

            
69
    #[command(subcommand)]
70
    cmd: Command,
71
}
72

            
73
#[derive(Subcommand, Debug)]
74
enum Command {
75
    /// Print the software version
76
    Version,
77

            
78
    /// Access to accounts
79
    #[command(subcommand)]
80
    Account(AccountCmd),
81

            
82
    /// Access to transactions
83
    #[command(subcommand)]
84
    Transaction(TransactionCmd),
85

            
86
    /// Access to commodities
87
    #[command(subcommand)]
88
    Commodity(CommodityCmd),
89

            
90
    /// Access to tags
91
    #[command(subcommand)]
92
    Tag(TagCmd),
93

            
94
    /// Access to transaction templates
95
    #[command(subcommand)]
96
    Template(TemplateCmd),
97

            
98
    /// Access to scripts
99
    #[command(subcommand)]
100
    Script(ScriptCmd),
101

            
102
    /// Access to configuration
103
    #[command(subcommand)]
104
    Config(ConfigCmd),
105

            
106
    /// Access to SQL database
107
    #[command(subcommand)]
108
    Sql(SqlCmd),
109

            
110
    /// Text-rendered report charts
111
    #[command(subcommand)]
112
    Reports(ReportsCmd),
113

            
114
    /// Manage SSH public keys for remote TUI access
115
    #[command(subcommand, name = "ssh-key")]
116
    SshKey(SshKeyCmd),
117

            
118
    /// Administrative reports about the stored data
119
    #[command(subcommand)]
120
    Admin(AdminCmd),
121
}
122

            
123
#[derive(Subcommand, Debug)]
124
enum AdminCmd {
125
    /// List the data problems migrations recorded instead of fixing
126
    Findings {
127
        /// Only the findings of this kind
128
        #[arg(long)]
129
        kind: Option<String>,
130
    },
131
    /// Open every stored transaction and template in the forms and save each
132
    /// transaction unchanged. It writes: aim it at a restored copy only
133
    #[command(name = "check-forms")]
134
    CheckForms {
135
        /// Confirms the database is a disposable restored copy
136
        #[arg(long)]
137
        disposable: bool,
138
    },
139
    /// List the stored templates and declared sources that name an account or
140
    /// commodity ambiguously or by a bare name, and check the trigger host
141
    /// resolves no names. Read-only
142
    #[command(name = "check-references")]
143
    CheckReferences {
144
        /// Directory of shipped source files (`.org`, `.nms`, `.lisp`) to scan
145
        #[arg(long)]
146
        sources: Option<std::path::PathBuf>,
147
    },
148
}
149

            
150
#[derive(Subcommand, Debug)]
151
enum SshKeyCmd {
152
    /// Register a public key for the current user
153
    Add {
154
        /// Path to a `.pub` OpenSSH public-key file
155
        #[arg(
156
            long,
157
            conflicts_with = "public_key",
158
            required_unless_present = "public_key"
159
        )]
160
        key_file: Option<String>,
161
        /// OpenSSH `authorized_keys` line passed inline
162
        #[arg(
163
            long,
164
            conflicts_with = "key_file",
165
            required_unless_present = "key_file"
166
        )]
167
        public_key: Option<String>,
168
        /// Optional human-readable label
169
        #[arg(long)]
170
        annotation: Option<String>,
171
    },
172
    /// List all keys for the current user
173
    List,
174
    /// Remove a key by its SHA-256 fingerprint
175
    Remove {
176
        /// Fingerprint, e.g. `SHA256:abc…`
177
        #[arg(long)]
178
        fingerprint: String,
179
    },
180
}
181

            
182
#[derive(Subcommand, Debug)]
183
enum AccountCmd {
184
    /// List all accounts
185
    List,
186
    /// Get the current balance and currency of an account
187
    Balance {
188
        #[arg(long)]
189
        account: Uuid,
190
    },
191
    #[command(flatten)]
192
    Forms(AccountForms),
193
    /// Merge one account into another: its splits, lots, budgets, sub-accounts
194
    /// and tags move, and it is deleted
195
    Merge(account_merge::MergeArgs),
196
}
197

            
198
#[derive(Subcommand, Debug)]
199
enum CommodityCmd {
200
    /// List all commodities
201
    List,
202
    #[command(flatten)]
203
    Forms(CommodityForms),
204
}
205

            
206
#[derive(Subcommand, Debug)]
207
enum TagCmd {
208
    /// List all tags
209
    List,
210
    /// Delete a tag with every link to it
211
    Delete {
212
        /// Id of the tag
213
        id: Uuid,
214
        /// Delete without asking; required when stdin is not a terminal
215
        #[arg(long)]
216
        yes: bool,
217
    },
218
    #[command(flatten)]
219
    Forms(TagForms),
220
}
221

            
222
#[derive(Subcommand, Debug)]
223
enum ConfigCmd {
224
    /// Print the value from config; there is no get form, so it stays on `get-config`
225
    Get {
226
        #[arg(long)]
227
        name: String,
228
    },
229
    #[command(flatten)]
230
    Forms(ConfigForms),
231
}
232

            
233
#[derive(Subcommand, Debug)]
234
enum SqlCmd {
235
    /// Raw select of SQL table
236
    Selcol {
237
        #[arg(long)]
238
        field: String,
239
        #[arg(long)]
240
        table: String,
241
    },
242
}
243

            
244
#[tokio::main]
245
15
async fn main() -> anyhow::Result<()> {
246
15
    let cli = Cli::parse();
247

            
248
15
    server::telemetry::init_logging(cli.loglevel, LevelFilter::WARN)?;
249

            
250
15
    if let Command::Admin(AdminCmd::CheckForms { disposable }) = &cli.cmd {
251
15
        let database = cli
252
15
            .database
253
15
            .clone()
254
            .or_else(|| std::env::var("DATABASE_URL").ok());
255
15
        if let Err(message) = disposable::require(*disposable, database.as_deref()) {
256
15
            eprintln!("Error: {message}");
257
15
            std::process::exit(1);
258
        }
259
    }
260

            
261
    let setopt = cli.setopt.map(|p| (p.field, p.content));
262
    start_server(cli.database, setopt).await?;
263

            
264
    let session_result = Session::new(ScriptCtx::new(cli.userid));
265
    let mut session = match session_result {
266
        Ok(s) => s,
267
        Err(e) => {
268
            eprintln!("Error: session init failed: {e}");
269
            std::process::exit(1);
270
        }
271
    };
272

            
273
    let outcome = dispatch_command(&mut session, cli.userid, cli.cmd).await;
274
15
    match outcome {
275
15
        Ok(()) => Ok(()),
276
15
        Err(err) => {
277
15
            eprintln!("{}", error_text(&err));
278
15
            std::process::exit(1);
279
15
        }
280
15
    }
281
15
}
282

            
283
async fn dispatch_command(
284
    session: &mut Session,
285
    userid: Uuid,
286
    cmd: Command,
287
) -> Result<(), CommandError> {
288
    match cmd {
289
        Command::Version => eval_print(session, "(get-version)", RenderMode::Scalar).await,
290
        Command::Account(c) => run_account(session, userid, c).await,
291
        Command::Transaction(c) => transaction::run(session, c).await,
292
        Command::Commodity(c) => run_commodity(session, c).await,
293
        Command::Tag(c) => run_tag(session, c).await,
294
        Command::Template(c) => template::run(session, c).await,
295
        Command::Script(c) => script::run(session, c).await,
296
        Command::Config(c) => run_config(session, c).await,
297
        Command::Sql(c) => run_sql(c).await,
298
        Command::Reports(c) => reports::run(session, c).await,
299
        Command::SshKey(c) => run_ssh_key(session, c).await,
300
        Command::Admin(c) => run_admin(c).await,
301
    }
302
}
303

            
304
3
fn error_text(err: &CommandError) -> String {
305
3
    match err {
306
2
        CommandError::FormInvalid(_) => err.to_string(),
307
1
        other => format!("Error: {other}"),
308
    }
309
3
}
310

            
311
async fn run_account(
312
    session: &mut Session,
313
    _userid: Uuid,
314
    cmd: AccountCmd,
315
) -> Result<(), CommandError> {
316
    match cmd {
317
        AccountCmd::List => eval_print(session, "(list-accounts)", RenderMode::AccountList).await,
318
        AccountCmd::Balance { account } => {
319
            let form = format!("(get-balances {})", escape_str(&account.to_string()));
320
            eval_print(session, &form, RenderMode::BalanceList).await
321
        }
322
        AccountCmd::Forms(forms) => forms.run(session).await,
323
        AccountCmd::Merge(args) => account_merge::run(session, &args).await,
324
    }
325
}
326

            
327
async fn run_commodity(session: &mut Session, cmd: CommodityCmd) -> Result<(), CommandError> {
328
    match cmd {
329
        CommodityCmd::List => {
330
            eval_print(session, "(list-commodities)", RenderMode::CommodityList).await
331
        }
332
        CommodityCmd::Forms(forms) => forms.run(session).await,
333
    }
334
}
335

            
336
async fn run_tag(session: &mut Session, cmd: TagCmd) -> Result<(), CommandError> {
337
    match cmd {
338
        TagCmd::List => eval_print(session, "(list-tags)", RenderMode::TagList).await,
339
        TagCmd::Delete { id, yes } => {
340
            let stdin = std::io::stdin();
341
            if !delete_tag_confirmed(session, id, yes, stdin.is_terminal(), stdin.lock()).await? {
342
                eprintln!("Cancelled");
343
            }
344
            Ok(())
345
        }
346
        TagCmd::Forms(forms) => forms.run(session).await,
347
    }
348
}
349

            
350
async fn run_config(session: &mut Session, cmd: ConfigCmd) -> Result<(), CommandError> {
351
    match cmd {
352
        ConfigCmd::Get { name } => {
353
            let form = format!("(get-config {})", escape_str(&name));
354
            eval_print(session, &form, RenderMode::ConfigValue).await
355
        }
356
        ConfigCmd::Forms(forms) => forms.run(session).await,
357
    }
358
}
359

            
360
async fn run_sql(cmd: SqlCmd) -> Result<(), CommandError> {
361
    match cmd {
362
        SqlCmd::Selcol { field, table } => {
363
            let mut args: HashMap<&str, Argument> = HashMap::new();
364
            args.insert("field", Argument::String(field));
365
            args.insert("table", Argument::String(table));
366
            run_and_print(&CliSelectColumn, args).await
367
        }
368
    }
369
}
370

            
371
async fn run_admin(cmd: AdminCmd) -> Result<(), CommandError> {
372
    match cmd {
373
        AdminCmd::Findings { kind } => {
374
            let mut args: HashMap<&str, Argument> = HashMap::new();
375
            if let Some(kind) = kind {
376
                args.insert("kind", Argument::String(kind));
377
            }
378
            run_and_print(&CliListDataFindings, args).await
379
        }
380
        AdminCmd::CheckForms { .. } => check_forms().await,
381
        AdminCmd::CheckReferences { sources } => {
382
            let admin = ADMIN_USER_ID
383
                .parse::<Uuid>()
384
                .map_err(|e| CommandError::Argument(format!("admin id: {e}")))?;
385
            references::run(admin, sources.as_deref()).await
386
        }
387
    }
388
}
389

            
390
async fn check_forms() -> Result<(), CommandError> {
391
    let admin = ADMIN_USER_ID
392
        .parse::<Uuid>()
393
        .map_err(|e| CommandError::Argument(format!("admin id: {e}")))?;
394
    let report = rpc::preflight::check_forms(admin)
395
        .await
396
        .map_err(|e| CommandError::Command(e.to_string()))?;
397
    report.problems.iter().for_each(|p| println!("{p}"));
398
    println!("{}", report.summary());
399
    match report.problems.is_empty() {
400
        true => Ok(()),
401
        false => Err(CommandError::Command("form preflight failed".to_string())),
402
    }
403
}
404

            
405
async fn run_ssh_key(session: &mut Session, cmd: SshKeyCmd) -> Result<(), CommandError> {
406
    match cmd {
407
        SshKeyCmd::Add {
408
            key_file,
409
            public_key,
410
            annotation,
411
        } => ssh_key::add(session, key_file, public_key, annotation).await,
412
        SshKeyCmd::List => eval_print(session, "(list-ssh-keys)", RenderMode::SshKeyList).await,
413
        SshKeyCmd::Remove { fingerprint } => {
414
            let form = build_remove_ssh_key_form(&fingerprint);
415
            eval_print(session, &form, RenderMode::BoolSuccess).await
416
        }
417
    }
418
}
419

            
420
#[cfg(test)]
421
mod tests;