lmrc-cli 0.3.16

CLI tool for scaffolding LMRC Stack infrastructure projects
Documentation
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use crate::error::{CliError, Result};
use colored::Colorize;
use lmrc_config_validator::LmrcConfig;
use lmrc_pipeline::steps::{
    BootstrapInitStep, ProvisionStep, SetupDatabaseStep, SetupDnsStep, SetupK8sStep,
    SetupLoadBalancerStep, SetupQueueStep, SetupSslStep, SetupVaultStep,
};
use lmrc_pipeline::{Pipeline, PipelineContext};
use std::fs;
use std::path::PathBuf;

/// Initialize git repository
pub async fn git() -> Result<()> {
    println!("{}", "Initializing git repository...".green().bold());

    validate_lmrc_workspace()?;

    // Check if git is already initialized
    if PathBuf::from(".git").exists() {
        println!("  {} Git repository already initialized", "".bright_green());
        return Ok(());
    }

    // Initialize git
    std::process::Command::new("git")
        .arg("init")
        .status()
        .map_err(|e| CliError::IoError(format!("Failed to initialize git: {}", e)))?;

    // Create initial commit
    std::process::Command::new("git")
        .args(&["add", "."])
        .status()
        .map_err(|e| CliError::IoError(format!("Failed to stage files: {}", e)))?;

    std::process::Command::new("git")
        .args(&["commit", "-m", "Initial commit"])
        .status()
        .map_err(|e| CliError::IoError(format!("Failed to create initial commit: {}", e)))?;

    println!("  {} Git repository initialized", "".bright_green());
    println!("\nNext steps:");
    println!("  - lmrc setup remote  # Configure GitLab remote");
    println!("  - lmrc setup secrets # Upload CI/CD secrets");

    Ok(())
}

/// Configure GitLab remote and push code
pub async fn remote() -> Result<()> {
    println!("{}", "Configuring GitLab remote...".green().bold());

    validate_lmrc_workspace()?;

    // Load config to get GitLab details
    let config = load_config()?;

    let gitlab_config = config
        .infrastructure
        .gitlab
        .as_ref()
        .ok_or_else(|| CliError::Config("GitLab configuration not found in lmrc.toml".to_string()))?;

    let remote_url = format!("{}/{}/{}.git", gitlab_config.url, gitlab_config.namespace, config.project.name);

    println!("  {} Remote URL: {}", "".bright_blue(), remote_url.bright_white());

    // Check if remote already exists
    let output = std::process::Command::new("git")
        .args(&["remote", "get-url", "origin"])
        .output();

    if output.is_ok() && output.unwrap().status.success() {
        println!("  {} Remote 'origin' already configured", "".bright_green());
    } else {
        // Add remote
        std::process::Command::new("git")
            .args(&["remote", "add", "origin", &remote_url])
            .status()
            .map_err(|e| CliError::IoError(format!("Failed to add remote: {}", e)))?;

        println!("  {} Remote 'origin' configured", "".bright_green());
    }

    // Push to remote
    println!("  {} Pushing to remote...", "".bright_blue());
    let status = std::process::Command::new("git")
        .args(&["push", "-u", "origin", "main"])
        .status()
        .map_err(|e| CliError::IoError(format!("Failed to push: {}", e)))?;

    if status.success() {
        println!("  {} Code pushed to GitLab", "".bright_green());
    } else {
        return Err(CliError::IoError("Failed to push to remote".to_string()));
    }

    println!("\nNext step:");
    println!("  - lmrc setup secrets # Upload CI/CD secrets");

    Ok(())
}

/// Upload CI/CD secrets to GitLab
pub async fn secrets() -> Result<()> {
    println!("{}", "Uploading CI/CD secrets to GitLab...".green().bold());

    validate_lmrc_workspace()?;

    let env_file = check_env_bootstrap_file()?;
    let (gitlab_url, gitlab_token, gitlab_project) = load_required_env_vars(&env_file)?;
    let config = load_config()?;

    let bootstrap_step = BootstrapInitStep::new(env_file, gitlab_url, gitlab_token, gitlab_project);

    let ctx = PipelineContext::new(config)
        .map_err(|e| CliError::Pipeline(format!("Failed to create pipeline context: {}", e)))?;

    Pipeline::new(ctx)
        .add_step(bootstrap_step)
        .run()
        .await
        .map_err(|e| CliError::Pipeline(format!("Failed to upload secrets: {}", e)))?;

    println!("  {} CI/CD secrets uploaded to GitLab", "".bright_green());

    Ok(())
}

/// Provision servers on cloud provider
pub async fn servers() -> Result<()> {
    println!("{}", "Provisioning servers...".green().bold());

    validate_lmrc_workspace()?;
    let config = load_config()?;

    let ctx = PipelineContext::new(config)
        .map_err(|e| CliError::Pipeline(format!("Failed to create pipeline context: {}", e)))?;

    Pipeline::new(ctx)
        .add_step(ProvisionStep::default())
        .run()
        .await
        .map_err(|e| CliError::Pipeline(format!("Server provisioning failed: {}", e)))?;

    println!("  {} Servers provisioned", "".bright_green());
    println!("\nNext step:");
    println!("  - lmrc setup network # Configure networking");

    Ok(())
}

/// Configure networking and firewall rules
pub async fn network() -> Result<()> {
    println!("{}", "Configuring networking...".green().bold());

    validate_lmrc_workspace()?;

    // TODO: Implement network setup step in lmrc-pipeline
    println!("  {} Network configuration is handled during server provisioning", "".bright_blue());
    println!("\nNext step:");
    println!("  - lmrc setup kubernetes # Install Kubernetes");

    Ok(())
}

/// Install and configure Kubernetes (K3s)
pub async fn kubernetes() -> Result<()> {
    println!("{}", "Installing Kubernetes (K3s)...".green().bold());

    validate_lmrc_workspace()?;
    let config = load_config()?;

    let ctx = PipelineContext::new(config)
        .map_err(|e| CliError::Pipeline(format!("Failed to create pipeline context: {}", e)))?;

    Pipeline::new(ctx)
        .add_step(SetupK8sStep)
        .run()
        .await
        .map_err(|e| CliError::Pipeline(format!("Kubernetes setup failed: {}", e)))?;

    println!("  {} Kubernetes installed", "".bright_green());
    println!("\nNext steps:");
    println!("  - lmrc setup database # Setup PostgreSQL");
    println!("  - lmrc setup ingress  # Setup ingress controller");

    Ok(())
}

/// Setup PostgreSQL database
pub async fn database() -> Result<()> {
    println!("{}", "Setting up PostgreSQL...".green().bold());

    validate_lmrc_workspace()?;
    let config = load_config()?;

    let ctx = PipelineContext::new(config)
        .map_err(|e| CliError::Pipeline(format!("Failed to create pipeline context: {}", e)))?;

    Pipeline::new(ctx)
        .add_step(SetupDatabaseStep)
        .run()
        .await
        .map_err(|e| CliError::Pipeline(format!("Database setup failed: {}", e)))?;

    println!("  {} PostgreSQL configured", "".bright_green());

    Ok(())
}

/// Setup RabbitMQ message queue
pub async fn queue() -> Result<()> {
    println!("{}", "Setting up RabbitMQ...".green().bold());

    validate_lmrc_workspace()?;
    let config = load_config()?;

    let ctx = PipelineContext::new(config)
        .map_err(|e| CliError::Pipeline(format!("Failed to create pipeline context: {}", e)))?;

    Pipeline::new(ctx)
        .add_step(SetupQueueStep)
        .run()
        .await
        .map_err(|e| CliError::Pipeline(format!("Queue setup failed: {}", e)))?;

    println!("  {} RabbitMQ installed and configured", "".bright_green());

    Ok(())
}

/// Configure DNS records (Cloudflare)
pub async fn dns() -> Result<()> {
    println!("{}", "Configuring DNS records...".green().bold());

    validate_lmrc_workspace()?;
    let config = load_config()?;

    let ctx = PipelineContext::new(config)
        .map_err(|e| CliError::Pipeline(format!("Failed to create pipeline context: {}", e)))?;

    Pipeline::new(ctx)
        .add_step(SetupDnsStep)
        .run()
        .await
        .map_err(|e| CliError::Pipeline(format!("DNS setup failed: {}", e)))?;

    println!("  {} DNS records configured", "".bright_green());

    Ok(())
}

/// Setup ingress controller (Traefik)
pub async fn ingress() -> Result<()> {
    println!("{}", "Setting up ingress controller...".green().bold());

    validate_lmrc_workspace()?;

    // TODO: Implement ingress setup step in lmrc-pipeline
    println!("  {} Ingress is configured as part of K3s setup", "".bright_blue());

    Ok(())
}

/// Setup complete infrastructure (servers + network + kubernetes + database + queue + dns + ingress)
pub async fn infra() -> Result<()> {
    println!("{}", "Setting up complete infrastructure...".green().bold());
    println!("{}", "=".repeat(60).bright_blue());

    validate_lmrc_workspace()?;
    let config = load_config()?;

    let ctx = PipelineContext::new(config.clone())
        .map_err(|e| CliError::Pipeline(format!("Failed to create pipeline context: {}", e)))?;

    let mut pipeline = Pipeline::new(ctx);
    pipeline = pipeline
        .add_step(ProvisionStep::default())
        .add_step(SetupLoadBalancerStep)  // Load balancer MUST be after provisioning (needs servers/network) and BEFORE DNS (DNS needs LB IP)
        .add_step(SetupVaultStep)  // Vault MUST be set up BEFORE database and queue
        .add_step(SetupK8sStep)
        .add_step(SetupDatabaseStep);  // Database gets credentials FROM Vault

    // Only add queue step if RabbitMQ is configured
    if config.infrastructure.rabbitmq.is_some() {
        pipeline = pipeline.add_step(SetupQueueStep);  // Queue gets credentials FROM Vault
    }

    // Add SSL/TLS certificate setup AFTER load balancer and BEFORE DNS
    pipeline = pipeline
        .add_step(SetupSslStep::default())  // SSL must be after LB (needs LB to exist) and before DNS (DNS may need to enable proxying)
        .add_step(SetupDnsStep);

    pipeline.run()
        .await
        .map_err(|e| CliError::Pipeline(format!("Infrastructure setup failed: {}", e)))?;

    println!();
    println!("{}", "=".repeat(60).bright_green());
    println!("{}", "Infrastructure setup complete!".bright_green().bold());
    println!("{}", "=".repeat(60).bright_green());
    println!("\nNote: Some components may require manual installation steps. Check output above for details.");

    Ok(())
}

/// Setup everything (git + remote + secrets + infra)
pub async fn all() -> Result<()> {
    println!("{}", "Setting up complete project...".bright_blue().bold());
    println!("{}", "=".repeat(60).bright_blue());

    // Git setup
    git().await?;
    println!();

    // Remote setup
    remote().await?;
    println!();

    // Secrets upload
    secrets().await?;
    println!();

    // Infrastructure setup
    infra().await?;

    println!();
    println!("{}", "=".repeat(60).bright_green());
    println!("{}", "Complete setup finished!".bright_green().bold());
    println!("{}", "=".repeat(60).bright_green());
    println!("\nYour project is fully configured and ready for deployment.");

    Ok(())
}

// Helper functions

fn validate_lmrc_workspace() -> Result<()> {
    if !PathBuf::from("lmrc.toml").exists() {
        return Err(CliError::Config(
            "lmrc.toml not found. This command must be run from an LMRC-generated project root."
                .to_string(),
        ));
    }

    if !PathBuf::from("Cargo.toml").exists() {
        return Err(CliError::Config(
            "Cargo.toml not found. This command must be run from an LMRC-generated project root."
                .to_string(),
        ));
    }

    Ok(())
}

fn load_config() -> Result<LmrcConfig> {
    LmrcConfig::from_file(&PathBuf::from("lmrc.toml"))
        .map_err(|e| CliError::Config(format!("Failed to load lmrc.toml: {}", e)))
}

fn check_env_bootstrap_file() -> Result<PathBuf> {
    let env_file = PathBuf::from(".env.bootstrap");

    if !env_file.exists() {
        return Err(CliError::Config(
            ".env.bootstrap file not found.\n\n\
            Please create a .env.bootstrap file with your CI/CD variables:\n\n\
            # Required variables:\n\
            GITLAB_URL=https://gitlab.com\n\
            GITLAB_TOKEN=your-gitlab-token\n\
            GITLAB_PROJECT=your-org/your-project\n\n\
            # Infrastructure tokens:\n\
            HETZNER_API_TOKEN=your-hetzner-token\n\
            CLOUDFLARE_API_TOKEN=your-cloudflare-token\n\n\
            # Add other variables as needed...\n"
                .to_string(),
        ));
    }

    Ok(env_file)
}

fn load_required_env_vars(env_file: &PathBuf) -> Result<(String, String, String)> {
    let content = fs::read_to_string(env_file)
        .map_err(|e| CliError::IoError(format!("Failed to read .env.bootstrap: {}", e)))?;

    let mut gitlab_url = None;
    let mut gitlab_token = None;
    let mut gitlab_project = None;

    for line in content.lines() {
        let line = line.trim();

        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        if let Some((key, value)) = line.split_once('=') {
            let key = key.trim();
            let value = value.trim();

            let value = if (value.starts_with('"') && value.ends_with('"'))
                || (value.starts_with('\'') && value.ends_with('\''))
            {
                &value[1..value.len() - 1]
            } else {
                value
            };

            match key {
                "GITLAB_URL" => gitlab_url = Some(value.to_string()),
                "GITLAB_TOKEN" => gitlab_token = Some(value.to_string()),
                "GITLAB_PROJECT" => gitlab_project = Some(value.to_string()),
                _ => {}
            }
        }
    }

    let gitlab_url = gitlab_url
        .ok_or_else(|| CliError::Config("GITLAB_URL not found in .env.bootstrap".to_string()))?;

    let gitlab_token = gitlab_token
        .ok_or_else(|| CliError::Config("GITLAB_TOKEN not found in .env.bootstrap".to_string()))?;

    let gitlab_project = gitlab_project.ok_or_else(|| {
        CliError::Config("GITLAB_PROJECT not found in .env.bootstrap".to_string())
    })?;

    Ok((gitlab_url, gitlab_token, gitlab_project))
}