//! Passphrase derivation for cryptsetup devices.
//!
//! This module derives passphrases for encrypted block devices using:
//! 1. The innate ID of the block device (via block-device-id crate)
//! 2. HMAC-SHA256 using a firmware OTP key

use std::io;
use std::os::unix::ffi::OsStrExt;

use crate::rpifwcrypto;

/// The OTP key ID to use for HMAC operations.
/// Key 1 is typically the device-unique private key.
const OTP_KEY_ID: u32 = 1;

/// Derive a passphrase for a block device.
///
/// This function:
/// 1. Gets the innate ID of the block device (e.g., MMC CID or NVMe serial)
/// 2. Computes HMAC-SHA256 of the ID using a firmware OTP key
/// 3. Returns the HMAC as a hex string (the passphrase)
///
/// # Arguments
///
/// * `device` - The device path from the cryptsetup request
///
/// # Returns
///
/// The derived passphrase as a 64-character lowercase hex string.
pub fn derive_passphrase(device: &str) -> Result<String, io::Error> {
    let block_id = block_device_id::get_id_by_path(device).map_err(|e| {
        io::Error::new(
            io::ErrorKind::Other,
            format!("failed to get device ID for {}: {}", device, e),
        )
    })?;

    rpifwcrypto::hmac_sha256(OTP_KEY_ID, block_id.id.as_os_str().as_bytes()).map_err(Into::into)
}
