Skip to main content

nuwax_cli/
init.rs

1use anyhow::Result;
2use client_core::{
3    ClientRegisterRequest, api::ApiClient, config::AppConfig, constants::config, database::Database,
4};
5use tracing::{info, warn};
6
7/// 运行独立的初始化流程
8pub async fn run_init(force: bool) -> Result<()> {
9    info!("🦆 Nuwax Cli ent Initialization");
10    info!("======================");
11
12    // 检查是否已经初始化过
13    if !force
14        && (client_core::constants::config::get_config_file_path().exists()
15            || config::get_database_path().exists())
16    {
17        warn!("⚠️  Detected existing configuration or database files");
18        info!("Use --force flag to reinitialize");
19        info!("Example: nuwax-cli init --force");
20        return Ok(());
21    }
22
23    info!("📋 Step 1: Create configuration and directory structure");
24
25    // 创建默认配置
26    let config = AppConfig::default();
27    config.save_to_file("config.toml")?;
28    info!("   ✅ Created configuration file: config.toml");
29
30    // 创建必要的目录结构
31    std::fs::create_dir_all("docker")?;
32    std::fs::create_dir_all(&config.backup.storage_dir)?;
33    config.ensure_cache_dirs()?;
34    info!("   ✅ Created directory structure:");
35    info!("      - docker/                (Docker service files directory)");
36    info!(
37        "      - {dir}         (Backup storage directory)",
38        dir = config.backup.storage_dir
39    );
40    info!(
41        "      - {dir}    (Cache directory)",
42        dir = config.cache.cache_dir
43    );
44    info!(
45        "      - {dir} (Download cache directory)",
46        dir = config.cache.download_dir
47    );
48
49    info!("📋 Step 2: Initialize database");
50
51    // 初始化数据库
52    let db_path = config::get_database_path();
53    let database = Database::connect(&db_path).await?;
54
55    // 显式初始化数据库表结构(只在 init 时执行)
56    database.init_database().await?;
57
58    info!(
59        "   ✅ Created DuckDB database: {path}",
60        path = db_path.display()
61    );
62
63    // 生成新的客户端UUID
64    let client_uuid = database.get_or_create_client_uuid().await?;
65    info!("   ✅ Generated client UUID: {uuid}", uuid = client_uuid);
66
67    info!("📋 Step 3: Register client with server");
68
69    // 收集系统信息并注册客户端
70    let request = ClientRegisterRequest {
71        os: std::env::consts::OS.to_string(),
72        arch: std::env::consts::ARCH.to_string(),
73    };
74
75    // 创建API客户端(注册时不需要client_id)
76    let api_client = ApiClient::new(None, None);
77    match api_client.register_client(request).await {
78        Ok(server_client_id) => {
79            info!(
80                "   ✅ Client registered successfully, received client ID: {id}",
81                id = server_client_id
82            );
83
84            // 保存服务端返回的client_id到数据库,覆盖本地生成的UUID
85            database.update_client_id(&server_client_id).await?;
86            info!("   ✅ Client ID saved to database");
87        }
88        Err(e) => {
89            warn!(
90                "   ⚠️  Client registration failed: {error} (can retry later)",
91                error = e.to_string()
92            );
93            info!("   💡 This will not affect local functionality");
94        }
95    }
96
97    info!("🎉 Initialization complete!");
98    info!("");
99    info!("📝 Next steps:");
100    info!("   1️⃣  Run 'nuwax-cli upgrade' to download Docker service package");
101    info!("       - Or run 'nuwax-cli upgrade --force' to force full download");
102    info!("       - Or run 'nuwax-cli upgrade download' to prepare an offline deployment package");
103    info!("   2️⃣  Run 'nuwax-cli docker-service deploy' to deploy Docker services");
104    info!("   3️⃣  Run 'nuwax-cli docker-service start' to start Docker services");
105    info!("");
106    info!("🚀 Shortcut - Auto upgrade deploy:");
107    info!("   • Run 'nuwax-cli auto-upgrade-deploy run' for complete upgrade deployment");
108    info!(
109        "   • Run 'nuwax-cli auto-upgrade-deploy delay-time-deploy 2 --unit hours' to delay 2 hours"
110    );
111    info!("");
112    info!("💡 Tips:");
113    info!("   - Configuration file: config.toml (can be manually edited)");
114    info!(
115        "   - Database file: {path} (stores operation history and backup records)",
116        path = db_path.display()
117    );
118    info!("   - Use 'nuwax-cli --help' to see all available commands");
119    info!("   - Use 'nuwax-cli status' to check current system status");
120
121    Ok(())
122}