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
use crate::cmd::utils::Cmd;
use crate::constants::CLI_PATH;
use eyre::ContextCompat;
use std::fs::File;
use std::io::prelude::Write;

use clap::Parser;

#[derive(Debug, Clone, Parser)]
pub struct InitArgs {
    #[clap(short, long, help = "Private key to add to .env")]
    private_key: Option<String>,

    #[clap(
        short,
        long,
        help = "Trustblock auth token to add to .env",
        long_help = "Trustblock auth token, which you can get by navigating to /api/auth/session. If supplied, it will be added automatically to .env"
    )]
    auth_token: Option<String>,
}

impl Cmd for InitArgs {
    fn run(self) -> eyre::Result<()> {
        let home_dir = dirs::home_dir().wrap_err("Could not find home directory")?;

        let private_key = self.private_key.unwrap_or_default();
        let auth_token = self.auth_token.unwrap_or_default();

        // Create the path to the .trustblock directory
        let cli_dir = home_dir.join(CLI_PATH);

        // Create the .trustblock directory if it doesn't exist
        if !cli_dir.exists() {
            std::fs::create_dir(&cli_dir)?;
        }

        // Create the path to the .env file
        let env_path = cli_dir.join(".env");

        if !env_path.exists() {
            let mut env_file = File::create(&env_path)?;

            let env_data = format!("WALLET_KEY={private_key}\nAUTH_TOKEN={auth_token}");

            env_file.write_all(env_data.as_bytes())?;

            println!("Created .env file at {env_path:?}");
        }

        Ok(())
    }
}