//
// Syd: rock-solid application kernel
// src/syd-key.rs: Utility to generate AES-CTR Key and IV
//
// Copyright (c) 2024, 2025 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

use std::{io::Read, os::unix::ffi::OsStrExt, process::ExitCode};

use syd::{err::SydResult, hash::Key};

fn main() -> SydResult<ExitCode> {
    use lexopt::prelude::*;

    syd::set_sigpipe_dfl()?;

    // Parse CLI options.
    let mut opt_tag = None;

    let mut parser = lexopt::Parser::from_env();
    while let Some(arg) = parser.next()? {
        match arg {
            Short('h') => {
                help();
                return Ok(ExitCode::SUCCESS);
            }
            Short('t') => opt_tag = Some(parser.value()?),
            _ => return Err(arg.unexpected().into()),
        }
    }

    let key = if let Some(info) = opt_tag {
        // Read the key from stdin.
        let mut input = Vec::new();
        std::io::stdin().read_to_end(&mut input)?;
        // Remove any whitespace from the input.
        input.retain(|&byte| !byte.is_ascii_whitespace());
        let key = Key::from_hex(&input)?;
        // Derive the key using the given info.
        key.derive(None, info.as_bytes())
    } else {
        Key::random()?
    };

    println!("{}", key.as_hex());
    Ok(ExitCode::SUCCESS)
}

fn help() {
    println!("Usage: syd-key [-h] -t <tag-str>");
    println!("Utility to generate 256-bit AES-CTR key");
    println!("  -h        Print this help message and exit");
    println!("  -t <tag>  Read key-hex from standard input, derive a new key with HKDF using the given information tag");
}
