hodoe-cli 0.7.0

The official command-line interface tool for the HODOE.fr network.
use clap::{Parser, Subcommand};
use console::style;
use indicatif::{ProgressBar, ProgressStyle};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use tokio_util::io::ReaderStream;
use sha2::{Sha256, Digest};
use std::path::Path;

#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;

#[derive(Parser)]
#[command(
    name = "hodoe",
    version ,
    about = "⚡ Outil CLI officiel pour le réseau Hodoe.fr (Preuve de travail & Binaires)",
    long_about = "HODOE CLI est l'outil en ligne de commande dédié aux développeurs de systèmes embarqués et Doers.\n\
                  Il vous permet de publier vos preuves de travail matérielles en déployant vos binaires compilés\n\
                  (.uf2, .bin, .hex...) directement sur la plateforme Hodoe.fr."
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Connecter votre machine à votre compte HODOE avec votre jeton sécurisé
    Login {
        /// Jeton d'authentification ou clé API sécurisée HODOE 
        #[arg(short, long)]
        token: Option<String>,

        /// URL personnalisée du serveur API backend 
        #[arg(short, long)]
        url: Option<String>,
    },
    /// Publier et gérer vos projets et binaires embarqués
    Binary {
        /// Nom du projet ou du binaire
        name: String,

        #[command(subcommand)]
        action: BinaryActions,
    },
}

#[derive(Subcommand)]
enum BinaryActions {
    /// Téléverser et publier un binaire compilé sur le hub HODOE
    Push {
        /// Chemin vers le fichier binaire (.bin, .hex, .uf2, etc.)
        #[arg(short, long)]
        file: PathBuf,

        /// Architecture microcontrôleur cible (ex: rp2350, esp32, stm32, riscv)
        #[arg(short, long)]
        arch: String,

        /// Catégorie du binaire (ex: embedded, securite)
        #[arg(short, long)]
        category: String,

        /// URL du dépôt GitHub source (optionnel)
        #[arg(short, long)]
        github: Option<String>,

        /// Description détaillée du binaire ou des fonctionnalités (optionnel)
        #[arg(short, long)]
        description: Option<String>,
    },
}

#[derive(Serialize, Deserialize, Default)]
struct Config {
    api_key: Option<String>,
    api_url: Option<String>,
}

#[derive(Deserialize)]
struct PresignResponse {
    upload_url: String,
    public_url: String,
}

fn get_config_path() -> PathBuf {
    let mut path = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
    path.push(".hodoe");
    fs::create_dir_all(&path).ok();
    path.push("config.json");
    path
}

fn load_config() -> Config {
    let path = get_config_path();
    if let Ok(content) = fs::read_to_string(path) {
        serde_json::from_str(&content).unwrap_or_default()
    } else {
        Config::default()
    }
}

fn save_config(config: &Config) {
    let path = get_config_path();
    if let Ok(content) = serde_json::to_string_pretty(config) {
        if fs::write(&path, content).is_ok() {
            // Restriction des permissions du fichier de configuration sur UNIX (chmod 600)
            #[cfg(unix)]
            {
                let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o600));
            }
        }
    }
}

/// Calcule le hash SHA-256 d'un fichier de manière efficace par blocs
fn compute_sha256(path: &Path) -> Result<String, Box<dyn std::error::Error>> {
    let mut file = std::fs::File::open(path)?;
    let mut hasher = Sha256::new();
    let mut buffer = [0; 8192]; // Lecture par blocs de 8 Ko
    
    loop {
        let count = std::io::Read::read(&mut file, &mut buffer)?;
        if count == 0 {
            break;
        }
        hasher.update(&buffer[..count]);
    }
    
    let result = hasher.finalize();
    Ok(hex::encode(result))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();
    let config = load_config();

    let api_url = config
        .api_url
        .clone()
        .unwrap_or_else(|| "https://hodoe-api.onrender.com".to_string());

    match cli.command {
        Commands::Login { token, url } => {
            println!("{}", style("🔒 Configuration de la session HODOE...").cyan().bold());

            let final_token = match token {
                Some(t) => t,
                None => {
                    println!("{}", style("ℹ️ Rendez-vous sur https://hodoe.fr pour générer ou récupérer votre jeton d'accès sécurisé.").yellow());
                    eprintln!("{}", style("❌ Erreur : Veuillez fournir un jeton avec l'option --token <VOTRE_JETON>").red().bold());
                    return Ok(());
                }
            };

            let mut new_config = load_config();
            new_config.api_key = Some(final_token);
            if let Some(custom_url) = url {
                new_config.api_url = Some(custom_url);
            }
            save_config(&new_config);
            println!("{}", style("✅ Authentification réussie ! Identifiants sécurisés dans ~/.hodoe/config.json").green().bold());
        }
        Commands::Binary { name, action } => match action {
            BinaryActions::Push {
                file,
                arch,
                category,
                github,
                description,
            } => {
                let api_key = match &config.api_key {
                    Some(key) => key,
                    None => {
                        eprintln!("{}", style("❌ Vous n'êtes pas connecté.").red().bold());
                        eprintln!("   Exécutez d'abord : hodoe login --token <VOTRE_JETON>");
                        return Ok(());
                    }
                };

                if !file.exists() {
                    eprintln!(
                        "{}",
                        style(format!("❌ Erreur : Le fichier '{:?}' est introuvable.", file)).red().bold()
                    );
                    return Ok(());
                }

                // 1. Calcul du hash SHA-256 en local
                println!("{}", style("🔒 Calcul de l'empreinte SHA-256 du binaire...").cyan());
                let file_hash = match compute_sha256(&file) {
                    Ok(h) => {
                        println!("   🔑 SHA-256 : {}", style(&h).yellow());
                        h
                    }
                    Err(e) => {
                        eprintln!("{}", style(format!("❌ Erreur lors du calcul du SHA-256 : {}", e)).red());
                        return Ok(());
                    }
                };

                let tokio_file = tokio::fs::File::open(&file).await?;
                let file_size = tokio_file.metadata().await?.len();

                // Nettoyage et sécurisation du nom du fichier
                let file_name = file
                    .file_name()
                    .and_then(|n| n.to_str())
                    .map(|s| s.rsplit(['/', '\\']).next().unwrap_or("binary.bin"))
                    .unwrap_or("binary.bin");

                let client = Client::new();

                // 2. Obtention de l'URL d'upload temporaire (Presigned URL)
                println!("{}", style("🔑 Demande d'autorisation d'envoi au backend...").cyan());

                let presign_res = client
                    .post(format!("{}/api/v1/binaries/presign", api_url))
                    .header("Authorization", format!("Bearer {}", api_key))
                    .json(&serde_json::json!({ "filename": file_name }))
                    .send()
                    .await?;

                if !presign_res.status().is_success() {
                    let err = presign_res.text().await?;
                    eprintln!("{}", style(format!("❌ Erreur d'autorisation backend : {}", err)).red());
                    return Ok(());
                }

                let presign_data: PresignResponse = presign_res.json().await?;

                // 3. Téléversement du binaire vers le stockage via la Presigned URL (requête PUT)
                println!(
                    "{}",
                    style(format!("📦 Téléversement du binaire '{}' (arch: {}, cat: {}, {} octets)...", name, arch, category, file_size)).blue().bold()
                );

                let pb = ProgressBar::new(file_size);
                pb.set_style(
                    ProgressStyle::default_bar()
                        .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})")?
                        .progress_chars("#>-"),
                );

                let stream = ReaderStream::new(tokio_file);
                let body = reqwest::Body::wrap_stream(stream);

                let upload_res = client
                    .put(&presign_data.upload_url)
                    .header("Content-Type", "application/octet-stream")
                    .body(body)
                    .send()
                    .await?;

                if upload_res.status().is_success() {
                    pb.finish_with_message("✨ Téléversement physique réussi !");
                } else {
                    pb.abandon();
                    let err = upload_res.text().await?;
                    eprintln!("{}", style(format!("❌ Échec du téléversement : {}", err)).red());
                    return Ok(());
                }

                // 4. Enregistrement des métadonnées et de la signature sur HODOE
                println!("{}", style("📡 Enregistrement des métadonnées et de la signature sur HODOE...").magenta().bold());

                let payload = serde_json::json!({
                    "name": name,
                    "description": description,
                    "target_architecture": arch,
                    "category": category,
                    "file_url": presign_data.public_url,
                    "github_url": github,
                    "sha256_hash": file_hash
                });

                let response = client
                    .post(format!("{}/api/v1/binaries", api_url))
                    .header("Authorization", format!("Bearer {}", api_key))
                    .json(&payload)
                    .send()
                    .await?;

                if response.status().is_success() {
                    println!(
                        "{}",
                        style(format!("🚀 Le binaire '{}' a été publié avec succès sur HODOE !", name)).green().bold()
                    );
                } else {
                    let err_msg = response.text().await?;
                    eprintln!("{}", style(format!("❌ Échec de l'enregistrement API : {}", err_msg)).red());
                }
            }
        },
    }

    Ok(())
}