audb-cli 0.1.11

Command-line interface for AuDB database application framework
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! macOS launchd deployment implementation
//!
//! This module implements deployment to macOS launchd for managing services
//! that persist across reboots and can be controlled via launchctl.

use crate::commands::deploy::config::{DeploymentConfig, DeploymentTarget};
use crate::commands::deploy::state::DeploymentState;
use crate::commands::deploy::templates;
use anyhow::{Context, Result, anyhow};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Deploy the project to macOS launchd
pub async fn deploy(
    project_root: &Path,
    config: &DeploymentConfig,
    _force_rebuild: bool,
) -> Result<DeploymentState> {
    println!("Starting macOS launchd deployment...");

    // Validate target
    if config.target != DeploymentTarget::Daemon {
        return Err(anyhow!("Invalid deployment target for launchd"));
    }

    // Validate we're on macOS
    if !cfg!(target_os = "macos") {
        return Err(anyhow!("launchd deployment is only available on macOS"));
    }

    // Extract deployment parameters
    let project_name = project_root
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("audb-app");

    let service_label = format!("com.audb.{}", project_name);
    let port = config.port.unwrap_or(8080);

    // Check if service is already loaded
    if is_service_loaded(&service_label)? {
        println!("Warning: Service '{}' is already loaded", service_label);
        println!("Stopping existing service...");
        let _ = stop_service(&service_label);
    }

    // Step 1: Build release binary
    println!("Building release binary...");
    build_release_binary(project_root)?;

    // Step 2: Get binary path
    let binary_path = get_binary_path(project_root, project_name)?;

    if !binary_path.exists() {
        return Err(anyhow!(
            "Binary not found at {}. Build may have failed.",
            binary_path.display()
        ));
    }

    println!("Binary built at: {}", binary_path.display());

    // Step 3: Generate plist file
    println!("Generating launchd plist...");
    let plist_content = templates::generate_launchd_plist(&service_label, &binary_path, config);

    let plist_path = get_plist_path(&service_label)?;

    // Create directory if needed
    if let Some(parent) = plist_path.parent() {
        fs::create_dir_all(parent).context("Failed to create LaunchAgents directory")?;
    }

    fs::write(&plist_path, plist_content)
        .with_context(|| format!("Failed to write plist to {}", plist_path.display()))?;

    println!("Plist created at: {}", plist_path.display());

    // Step 4: Load service into launchd
    println!("Loading service into launchd...");
    load_service(&service_label, &plist_path)?;

    // Step 5: Enable service
    println!("Enabling service...");
    enable_service(&service_label)?;

    // Step 6: Wait a moment for service to start
    tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;

    // Step 7: Verify service is running
    let status = get_service_status(&service_label)?;

    if !status.running {
        println!("Warning: Service loaded but not running. Check logs for errors.");
        println!("Logs: /tmp/{}.log", service_label);
        println!("Errors: /tmp/{}.err", service_label);
    } else {
        println!("Service is running with PID: {}", status.pid.unwrap_or(0));
    }

    // Step 8: Create deployment state
    let state = DeploymentState {
        target: config.target,
        deployed_at: chrono::Utc::now(),
        service_label: service_label.clone(),
        project_name: project_name.to_string(),
    };

    // Save state
    state.save(project_root)?;

    println!("\nDeployment successful!");
    println!("Service label: {}", service_label);
    println!("Port: {}", port);
    println!("Plist: {}", plist_path.display());
    println!("\nView logs with: au deploy logs");
    println!("Check status with: au deploy status");
    println!("Stop with: au deploy stop");
    println!("\nManual commands:");
    println!("  launchctl list | grep {}", service_label);
    println!("  tail -f /tmp/{}.log", service_label);

    Ok(state)
}

/// Build release binary using cargo
fn build_release_binary(project_root: &Path) -> Result<()> {
    let status = Command::new("cargo")
        .arg("build")
        .arg("--release")
        .current_dir(project_root)
        .status()
        .context("Failed to run cargo build")?;

    if !status.success() {
        return Err(anyhow!("Cargo build failed"));
    }

    Ok(())
}

/// Get the path to the built binary
fn get_binary_path(project_root: &Path, project_name: &str) -> Result<PathBuf> {
    // The binary might be in a workspace target directory or project target directory
    // Try workspace first (going up to find workspace root)
    let mut current = project_root;
    let mut workspace_root = None;

    // Walk up to find workspace root (contains Cargo.toml with [workspace])
    while let Some(parent) = current.parent() {
        let cargo_toml = parent.join("Cargo.toml");
        if cargo_toml.exists() {
            if let Ok(content) = fs::read_to_string(&cargo_toml) {
                if content.contains("[workspace]") {
                    workspace_root = Some(parent);
                    break;
                }
            }
        }
        current = parent;
    }

    // Try workspace target first
    if let Some(workspace) = workspace_root {
        let workspace_binary = workspace.join("target").join("release").join(project_name);

        if workspace_binary.exists() {
            return Ok(workspace_binary);
        }
    }

    // Fall back to project target
    let project_binary = project_root
        .join("target")
        .join("release")
        .join(project_name);

    Ok(project_binary)
}

/// Get the path to the plist file
fn get_plist_path(service_label: &str) -> Result<PathBuf> {
    let home = std::env::var("HOME").context("HOME environment variable not set")?;
    Ok(PathBuf::from(home)
        .join("Library")
        .join("LaunchAgents")
        .join(format!("{}.plist", service_label)))
}

/// Check if service is already loaded
fn is_service_loaded(service_label: &str) -> Result<bool> {
    let output = Command::new("launchctl")
        .arg("list")
        .output()
        .context("Failed to run launchctl list")?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    Ok(stdout.contains(service_label))
}

/// Load service into launchd
fn load_service(service_label: &str, plist_path: &Path) -> Result<()> {
    let uid = get_user_id()?;
    let domain = format!("gui/{}", uid);

    let status = Command::new("launchctl")
        .arg("bootstrap")
        .arg(&domain)
        .arg(plist_path)
        .status()
        .context("Failed to bootstrap service")?;

    if !status.success() {
        return Err(anyhow!("Failed to bootstrap service '{}'", service_label));
    }

    Ok(())
}

/// Enable service
fn enable_service(service_label: &str) -> Result<()> {
    let uid = get_user_id()?;
    let service_target = format!("gui/{}/{}", uid, service_label);

    let status = Command::new("launchctl")
        .arg("enable")
        .arg(&service_target)
        .status()
        .context("Failed to enable service")?;

    if !status.success() {
        // Enable might fail if already enabled - that's ok
        println!("Note: Service may already be enabled");
    }

    Ok(())
}

/// Get current user ID
fn get_user_id() -> Result<String> {
    let output = Command::new("id")
        .arg("-u")
        .output()
        .context("Failed to get user ID")?;

    if !output.status.success() {
        return Err(anyhow!("Failed to get user ID"));
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Stop and unload service
pub async fn stop(project_root: &Path) -> Result<()> {
    let state = DeploymentState::load(project_root).context("No deployment state found")?;

    println!("Stopping launchd service '{}'...", state.service_label);

    stop_service(&state.service_label)?;

    // Remove plist file
    let plist_path = get_plist_path(&state.service_label)?;
    if plist_path.exists() {
        fs::remove_file(&plist_path)
            .with_context(|| format!("Failed to remove plist at {}", plist_path.display()))?;
        println!("Removed plist: {}", plist_path.display());
    }

    println!("Service stopped and unloaded");

    // Remove state file
    let state_path = project_root.join(".audb").join("deploy.toml");
    if state_path.exists() {
        fs::remove_file(&state_path).context("Failed to remove state file")?;
    }

    Ok(())
}

/// Stop service (idempotent)
fn stop_service(service_label: &str) -> Result<()> {
    let uid = get_user_id()?;
    let service_target = format!("gui/{}/{}", uid, service_label);

    // Disable service (ignore errors - might not be enabled)
    let _ = Command::new("launchctl")
        .arg("disable")
        .arg(&service_target)
        .status();

    // Bootout service (ignore errors - might not be loaded)
    let _ = Command::new("launchctl")
        .arg("bootout")
        .arg(&service_target)
        .status();

    Ok(())
}

/// Get service status
pub async fn status(project_root: &Path) -> Result<()> {
    let state = DeploymentState::load(project_root).context("No deployment state found")?;

    println!("Service: {}", state.service_label);
    println!("Project: {}", state.project_name);
    println!(
        "Deployed at: {}",
        state.deployed_at.format("%Y-%m-%d %H:%M:%S UTC")
    );

    let status = get_service_status(&state.service_label)?;

    if status.exists {
        println!("Status: Loaded");
        if status.running {
            println!("Running: Yes");
            if let Some(pid) = status.pid {
                println!("PID: {}", pid);
            }
        } else {
            println!("Running: No");
            if let Some(ref error) = status.error {
                println!("Error: {}", error);
            }
        }
    } else {
        println!("Status: Not loaded");
    }

    // Show log file locations
    println!("\nLog files:");
    println!("  stdout: /tmp/{}.log", state.service_label);
    println!("  stderr: /tmp/{}.err", state.service_label);

    Ok(())
}

/// Get service status by querying launchd
fn get_service_status(service_label: &str) -> Result<ServiceStatus> {
    let output = Command::new("launchctl")
        .arg("list")
        .arg(service_label)
        .output()
        .context("Failed to run launchctl list")?;

    if !output.status.success() {
        // Service not loaded
        return Ok(ServiceStatus {
            exists: false,
            running: false,
            pid: None,
            error: None,
        });
    }

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Parse output - format is:
    // {
    //   "Label" = "com.audb.myapp";
    //   "PID" = 12345;
    //   "LastExitStatus" = 0;
    // }

    let mut pid = None;
    let mut exit_status = None;

    for line in stdout.lines() {
        if line.contains("\"PID\"") {
            if let Some(value) = line.split('=').nth(1) {
                if let Ok(p) = value.trim().trim_end_matches(';').parse::<u32>() {
                    pid = Some(p);
                }
            }
        }
        if line.contains("\"LastExitStatus\"") {
            if let Some(value) = line.split('=').nth(1) {
                if let Ok(code) = value.trim().trim_end_matches(';').parse::<i32>() {
                    exit_status = Some(code);
                }
            }
        }
    }

    let running = pid.is_some();
    let error = if !running {
        exit_status.map(|code| format!("Last exit status: {}", code))
    } else {
        None
    };

    Ok(ServiceStatus {
        exists: true,
        running,
        pid,
        error,
    })
}

/// Show service logs
pub async fn logs(project_root: &Path, follow: bool, tail: Option<String>) -> Result<()> {
    let state = DeploymentState::load(project_root).context("No deployment state found")?;

    let log_path = format!("/tmp/{}.log", state.service_label);
    let err_path = format!("/tmp/{}.err", state.service_label);

    println!("Showing logs for service '{}'...\n", state.service_label);

    if follow {
        // Use tail -f to follow logs
        let mut cmd = Command::new("tail");
        cmd.arg("-f");

        if let Some(n) = tail {
            cmd.arg("-n").arg(n);
        }

        cmd.arg(&log_path);

        let status = cmd.status().context("Failed to tail log file")?;

        if !status.success() {
            return Err(anyhow!("Failed to follow logs"));
        }
    } else {
        // Show recent logs
        let n = tail.unwrap_or_else(|| "100".to_string());

        // Show stdout
        if PathBuf::from(&log_path).exists() {
            println!("=== stdout ({}) ===", log_path);
            let status = Command::new("tail")
                .arg("-n")
                .arg(&n)
                .arg(&log_path)
                .status()
                .context("Failed to read log file")?;

            if !status.success() {
                println!("Warning: Could not read stdout log");
            }
            println!();
        }

        // Show stderr
        if PathBuf::from(&err_path).exists() {
            println!("=== stderr ({}) ===", err_path);
            let status = Command::new("tail")
                .arg("-n")
                .arg(&n)
                .arg(&err_path)
                .status()
                .context("Failed to read error log")?;

            if !status.success() {
                println!("Warning: Could not read stderr log");
            }
        }
    }

    Ok(())
}

/// Restart service
pub async fn restart(project_root: &Path) -> Result<()> {
    let state = DeploymentState::load(project_root).context("No deployment state found")?;

    println!("Restarting service '{}'...", state.service_label);

    let uid = get_user_id()?;
    let service_target = format!("gui/{}/{}", uid, state.service_label);

    // Use kickstart to restart
    let status = Command::new("launchctl")
        .arg("kickstart")
        .arg("-k") // Kill existing instance
        .arg(&service_target)
        .status()
        .context("Failed to restart service")?;

    if !status.success() {
        return Err(anyhow!("Failed to restart service"));
    }

    println!("Service restarted successfully");

    Ok(())
}

/// Cleanup - force remove all traces of deployment
pub async fn cleanup(project_root: &Path) -> Result<()> {
    println!("Cleaning up deployment...");

    // Try to load state
    let service_label = if let Ok(state) = DeploymentState::load(project_root) {
        state.service_label.clone()
    } else {
        // No state file - try to guess service name from project
        let project_name = project_root
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("audb-app");
        format!("com.audb.{}", project_name)
    };

    // Stop service (idempotent - ignore errors)
    println!("Stopping service '{}'...", service_label);
    let _ = stop_service(&service_label);

    // Remove plist
    let plist_path = get_plist_path(&service_label)?;
    if plist_path.exists() {
        fs::remove_file(&plist_path)
            .with_context(|| format!("Failed to remove plist at {}", plist_path.display()))?;
        println!("Removed plist: {}", plist_path.display());
    }

    // Remove state file
    let state_path = project_root.join(".audb").join("deploy.toml");
    if state_path.exists() {
        fs::remove_file(&state_path).context("Failed to remove state file")?;
        println!("Removed state file");
    }

    println!("Cleanup complete!");

    Ok(())
}

/// Service status information
#[derive(Debug)]
struct ServiceStatus {
    exists: bool,
    running: bool,
    pid: Option<u32>,
    error: Option<String>,
}