//! Smoke-test binary: verify a `custom.txt` blob against the server's
//! branding public key. Run on the server before cutting a client release
//! to confirm the signing pipeline round-trips end-to-end:
//!
//!   cargo run --bin verify_branding -- /path/to/custom.txt
//!
//! Reads `branding_ed25519.pub` from CWD (the same path the admin UI
//! displays). Exits non-zero if verification fails or the JSON payload
//! doesn't decode as UTF-8.

use sodiumoxide::crypto::sign;
use std::process::ExitCode;

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().collect();
    let Some(path) = args.get(1) else {
        eprintln!("usage: verify_branding <path-to-custom.txt>");
        return ExitCode::from(2);
    };

    let pk_b64 = match std::fs::read_to_string("branding_ed25519.pub") {
        Ok(s) => s,
        Err(e) => {
            eprintln!("read branding_ed25519.pub: {e}");
            return ExitCode::from(1);
        }
    };
    let pk_bytes = match base64::decode(pk_b64.trim()) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("decode pubkey: {e}");
            return ExitCode::from(1);
        }
    };
    let Some(pk) = sign::PublicKey::from_slice(&pk_bytes) else {
        eprintln!("pubkey wrong length: {}", pk_bytes.len());
        return ExitCode::from(1);
    };

    let blob = match std::fs::read_to_string(path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("read {path}: {e}");
            return ExitCode::from(1);
        }
    };
    let signed = match base64::decode(blob.trim()) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("decode blob: {e}");
            return ExitCode::from(1);
        }
    };
    let body = match sign::verify(&signed, &pk) {
        Ok(b) => b,
        Err(_) => {
            eprintln!("signature verification FAILED");
            return ExitCode::from(1);
        }
    };

    match std::str::from_utf8(&body) {
        Ok(s) => {
            println!("{s}");
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("payload not utf-8: {e}");
            ExitCode::from(1)
        }
    }
}
