Skip to main content

opencode_cloud/
lib.rs

1//! opencode-cloud CLI - Manage your opencode cloud service
2//!
3//! This module contains the shared CLI implementation used by all binaries.
4
5mod commands;
6mod output;
7pub mod wizard;
8
9use anyhow::Result;
10use clap::{Parser, Subcommand};
11use console::style;
12use opencode_cloud_core::{
13    DockerClient, InstanceLock, SingletonError, config, get_version, load_config, load_hosts,
14    save_config,
15};
16
17/// Manage your opencode cloud service
18#[derive(Parser)]
19#[command(name = "opencode-cloud")]
20#[command(version = env!("CARGO_PKG_VERSION"))]
21#[command(about = "Manage your opencode cloud service", long_about = None)]
22#[command(after_help = get_banner())]
23struct Cli {
24    #[command(subcommand)]
25    command: Option<Commands>,
26
27    /// Increase verbosity level
28    #[arg(short, long, global = true, action = clap::ArgAction::Count)]
29    verbose: u8,
30
31    /// Suppress non-error output
32    #[arg(short, long, global = true)]
33    quiet: bool,
34
35    /// Disable colored output
36    #[arg(long, global = true)]
37    no_color: bool,
38
39    /// Target remote host (overrides default_host)
40    #[arg(long, global = true)]
41    host: Option<String>,
42}
43
44#[derive(Subcommand)]
45enum Commands {
46    /// Start the opencode service
47    Start(commands::StartArgs),
48    /// Stop the opencode service
49    Stop(commands::StopArgs),
50    /// Restart the opencode service
51    Restart(commands::RestartArgs),
52    /// Show service status
53    Status(commands::StatusArgs),
54    /// View service logs
55    Logs(commands::LogsArgs),
56    /// Register service to start on boot/login
57    Install(commands::InstallArgs),
58    /// Remove service registration
59    Uninstall(commands::UninstallArgs),
60    /// Manage configuration
61    Config(commands::ConfigArgs),
62    /// Run interactive setup wizard
63    Setup(commands::SetupArgs),
64    /// Manage container users
65    User(commands::UserArgs),
66    /// Manage bind mounts
67    Mount(commands::MountArgs),
68    /// Update to the latest version or rollback
69    Update(commands::UpdateArgs),
70    /// Open Cockpit web console
71    Cockpit(commands::CockpitArgs),
72    /// Manage remote hosts
73    Host(commands::HostArgs),
74}
75
76/// Get the ASCII banner for help display
77fn get_banner() -> &'static str {
78    r#"
79  ___  _ __   ___ _ __   ___ ___   __| | ___
80 / _ \| '_ \ / _ \ '_ \ / __/ _ \ / _` |/ _ \
81| (_) | |_) |  __/ | | | (_| (_) | (_| |  __/
82 \___/| .__/ \___|_| |_|\___\___/ \__,_|\___|
83      |_|                            cloud
84"#
85}
86
87/// Resolve which Docker client to use based on --host flag and default_host config
88///
89/// Returns (DockerClient, Option<host_name>) where host_name is Some for remote connections.
90///
91/// Resolution order:
92/// 1. --host flag (explicit)
93/// 2. default_host from hosts.json
94/// 3. Local Docker (no host_name)
95pub async fn resolve_docker_client(
96    maybe_host: Option<&str>,
97) -> anyhow::Result<(DockerClient, Option<String>)> {
98    let hosts = load_hosts().unwrap_or_default();
99
100    // Determine target host
101    let target_host = maybe_host
102        .map(String::from)
103        .or_else(|| hosts.default_host.clone());
104
105    match target_host {
106        Some(name) if name != "local" && !name.is_empty() => {
107            // Remote host requested
108            let host_config = hosts.get_host(&name).ok_or_else(|| {
109                anyhow::anyhow!(
110                    "Host '{name}' not found. Run 'occ host list' to see available hosts."
111                )
112            })?;
113
114            let client = DockerClient::connect_remote(host_config, &name).await?;
115            Ok((client, Some(name)))
116        }
117        _ => {
118            // Local Docker
119            let client = DockerClient::new()?;
120            Ok((client, None))
121        }
122    }
123}
124
125/// Format a message with optional host prefix
126///
127/// For remote hosts: "[prod-1] Starting container..."
128/// For local: "Starting container..."
129pub fn format_host_message(host_name: Option<&str>, message: &str) -> String {
130    match host_name {
131        Some(name) => format!("[{}] {}", style(name).cyan(), message),
132        None => message.to_string(),
133    }
134}
135
136pub fn run() -> Result<()> {
137    // Initialize tracing
138    tracing_subscriber::fmt::init();
139
140    let cli = Cli::parse();
141
142    // Configure color output
143    if cli.no_color {
144        console::set_colors_enabled(false);
145    }
146
147    // Load config (creates default if missing)
148    let config_path = config::paths::get_config_path()
149        .ok_or_else(|| anyhow::anyhow!("Could not determine config path"))?;
150
151    let config = match load_config() {
152        Ok(config) => {
153            // If config was just created, inform the user
154            if cli.verbose > 0 {
155                eprintln!(
156                    "{} Config loaded from: {}",
157                    style("[info]").cyan(),
158                    config_path.display()
159                );
160            }
161            config
162        }
163        Err(e) => {
164            // Display rich error for invalid config
165            eprintln!("{} Configuration error", style("Error:").red().bold());
166            eprintln!();
167            eprintln!("  {e}");
168            eprintln!();
169            eprintln!("  Config file: {}", style(config_path.display()).yellow());
170            eprintln!();
171            eprintln!(
172                "  {} Check the config file for syntax errors or unknown fields.",
173                style("Tip:").cyan()
174            );
175            eprintln!(
176                "  {} See schemas/config.example.jsonc for valid configuration.",
177                style("Tip:").cyan()
178            );
179            std::process::exit(1);
180        }
181    };
182
183    // Show verbose info if requested
184    if cli.verbose > 0 {
185        let data_dir = config::paths::get_data_dir()
186            .map(|p| p.display().to_string())
187            .unwrap_or_else(|| "unknown".to_string());
188        eprintln!(
189            "{} Config: {}",
190            style("[info]").cyan(),
191            config_path.display()
192        );
193        eprintln!("{} Data: {}", style("[info]").cyan(), data_dir);
194    }
195
196    // Store host flag for command handlers
197    let target_host = cli.host.clone();
198
199    // Check if wizard needed (missing auth and not running setup/config command)
200    let needs_wizard = !config.has_required_auth()
201        && !matches!(
202            cli.command,
203            Some(Commands::Setup(_)) | Some(Commands::Config(_))
204        );
205
206    if needs_wizard {
207        eprintln!(
208            "{} First-time setup required. Running wizard...",
209            style("Note:").cyan()
210        );
211        eprintln!();
212        let rt = tokio::runtime::Runtime::new()?;
213        let new_config = rt.block_on(wizard::run_wizard(Some(&config)))?;
214        save_config(&new_config)?;
215        eprintln!();
216        eprintln!(
217            "{} Setup complete! Run your command again, or use 'occ start' to begin.",
218            style("Success:").green().bold()
219        );
220        return Ok(());
221    }
222
223    match cli.command {
224        Some(Commands::Start(args)) => {
225            let rt = tokio::runtime::Runtime::new()?;
226            rt.block_on(commands::cmd_start(
227                &args,
228                target_host.as_deref(),
229                cli.quiet,
230                cli.verbose,
231            ))
232        }
233        Some(Commands::Stop(args)) => {
234            let rt = tokio::runtime::Runtime::new()?;
235            rt.block_on(commands::cmd_stop(&args, target_host.as_deref(), cli.quiet))
236        }
237        Some(Commands::Restart(args)) => {
238            let rt = tokio::runtime::Runtime::new()?;
239            rt.block_on(commands::cmd_restart(
240                &args,
241                target_host.as_deref(),
242                cli.quiet,
243                cli.verbose,
244            ))
245        }
246        Some(Commands::Status(args)) => {
247            let rt = tokio::runtime::Runtime::new()?;
248            rt.block_on(commands::cmd_status(
249                &args,
250                target_host.as_deref(),
251                cli.quiet,
252                cli.verbose,
253            ))
254        }
255        Some(Commands::Logs(args)) => {
256            let rt = tokio::runtime::Runtime::new()?;
257            rt.block_on(commands::cmd_logs(&args, target_host.as_deref(), cli.quiet))
258        }
259        Some(Commands::Install(args)) => {
260            let rt = tokio::runtime::Runtime::new()?;
261            rt.block_on(commands::cmd_install(&args, cli.quiet, cli.verbose))
262        }
263        Some(Commands::Uninstall(args)) => {
264            let rt = tokio::runtime::Runtime::new()?;
265            rt.block_on(commands::cmd_uninstall(&args, cli.quiet, cli.verbose))
266        }
267        Some(Commands::Config(cmd)) => commands::cmd_config(cmd, &config, cli.quiet),
268        Some(Commands::Setup(args)) => {
269            let rt = tokio::runtime::Runtime::new()?;
270            rt.block_on(commands::cmd_setup(&args, cli.quiet))
271        }
272        Some(Commands::User(args)) => {
273            let rt = tokio::runtime::Runtime::new()?;
274            rt.block_on(commands::cmd_user(
275                &args,
276                target_host.as_deref(),
277                cli.quiet,
278                cli.verbose,
279            ))
280        }
281        Some(Commands::Mount(args)) => {
282            let rt = tokio::runtime::Runtime::new()?;
283            rt.block_on(commands::cmd_mount(&args, cli.quiet, cli.verbose))
284        }
285        Some(Commands::Update(args)) => {
286            let rt = tokio::runtime::Runtime::new()?;
287            rt.block_on(commands::cmd_update(
288                &args,
289                target_host.as_deref(),
290                cli.quiet,
291                cli.verbose,
292            ))
293        }
294        Some(Commands::Cockpit(args)) => {
295            let rt = tokio::runtime::Runtime::new()?;
296            rt.block_on(commands::cmd_cockpit(
297                &args,
298                target_host.as_deref(),
299                cli.quiet,
300            ))
301        }
302        Some(Commands::Host(args)) => {
303            let rt = tokio::runtime::Runtime::new()?;
304            rt.block_on(commands::cmd_host(&args, cli.quiet, cli.verbose))
305        }
306        None => {
307            // No command - show a welcome message and hint to use --help
308            if !cli.quiet {
309                println!(
310                    "{} {}",
311                    style("opencode-cloud").cyan().bold(),
312                    style(get_version()).dim()
313                );
314                println!();
315                println!("Run {} for available commands.", style("--help").green());
316            }
317            Ok(())
318        }
319    }
320}
321
322/// Acquire the singleton lock for service management commands
323///
324/// This should be called before any command that manages the service
325/// (start, stop, restart, status, etc.) to ensure only one instance runs.
326/// Config commands don't need the lock as they're read-only or file-based.
327#[allow(dead_code)]
328fn acquire_singleton_lock() -> Result<InstanceLock, SingletonError> {
329    let pid_path = config::paths::get_data_dir()
330        .ok_or(SingletonError::InvalidPath)?
331        .join("opencode-cloud.pid");
332
333    InstanceLock::acquire(pid_path)
334}
335
336/// Display a rich error message when another instance is already running
337#[allow(dead_code)]
338fn display_singleton_error(err: &SingletonError) {
339    match err {
340        SingletonError::AlreadyRunning(pid) => {
341            eprintln!(
342                "{} Another instance is already running",
343                style("Error:").red().bold()
344            );
345            eprintln!();
346            eprintln!("  Process ID: {}", style(pid).yellow());
347            eprintln!();
348            eprintln!(
349                "  {} Stop the existing instance first:",
350                style("Tip:").cyan()
351            );
352            eprintln!("       {} stop", style("opencode-cloud").green());
353            eprintln!();
354            eprintln!(
355                "  {} If the process is stuck, kill it manually:",
356                style("Tip:").cyan()
357            );
358            eprintln!("       {} {}", style("kill").green(), pid);
359        }
360        SingletonError::CreateDirFailed(msg) => {
361            eprintln!(
362                "{} Failed to create data directory",
363                style("Error:").red().bold()
364            );
365            eprintln!();
366            eprintln!("  {msg}");
367            eprintln!();
368            if let Some(data_dir) = config::paths::get_data_dir() {
369                eprintln!("  {} Check permissions for:", style("Tip:").cyan());
370                eprintln!("       {}", style(data_dir.display()).yellow());
371            }
372        }
373        SingletonError::LockFailed(msg) => {
374            eprintln!("{} Failed to acquire lock", style("Error:").red().bold());
375            eprintln!();
376            eprintln!("  {msg}");
377        }
378        SingletonError::InvalidPath => {
379            eprintln!(
380                "{} Could not determine lock file path",
381                style("Error:").red().bold()
382            );
383            eprintln!();
384            eprintln!(
385                "  {} Ensure XDG_DATA_HOME or HOME is set.",
386                style("Tip:").cyan()
387            );
388        }
389    }
390}