hardcopy 1.0.1

Generate hard copies of keys, certs and secrets.
Documentation
use anyhow::{anyhow, Context, Result};
use genpdf::elements::{Break, Image, PageBreak, Paragraph, Text};
use genpdf::fonts;
use genpdf::style::Style;
use genpdf::{Document, Element as _, SimplePageDecorator};
use image::DynamicImage;
use libhardcopy::{HardCopy, HardCopySectionContent};

/// Font family names that follow genpdf's naming convention
/// (`{name}-Regular.ttf`, `{name}-Bold.ttf`, etc.).
const FONT_NAMES: &[&str] = &["LiberationMono", "NotoMono"];

/// System-wide font directories probed in order.
const SYSTEM_FONT_DIRS: &[&str] = &[
    "/usr/share/fonts/truetype/liberation2",
    "/usr/share/fonts/truetype/liberation",
    "/usr/share/fonts/liberation-fonts",
    "/usr/share/fonts/truetype/noto",
    "/usr/local/share/fonts",
];

fn candidate_dirs() -> Vec<String> {
    let mut dirs: Vec<String> = Vec::new();

    // XDG_DATA_HOME takes precedence; fall back to ~/.local/share per spec.
    let xdg_data_home = std::env::var("XDG_DATA_HOME").ok().or_else(|| {
        std::env::var("HOME")
            .ok()
            .map(|h| format!("{}/{}", h, ".local/share"))
    });
    if let Some(data_home) = xdg_data_home {
        dirs.push(format!("{}/fonts", data_home));
    }

    // Legacy user font dir.
    if let Ok(home) = std::env::var("HOME") {
        dirs.push(format!("{}/.fonts", home));
    }

    for &sys in SYSTEM_FONT_DIRS {
        dirs.push(sys.to_string());
    }
    dirs
}

type FontFamily = genpdf::fonts::FontFamily<genpdf::fonts::FontData>;

/// Try loading a full four-variant family, then fall back to using the
/// Regular file for all four slots (for fonts that only ship one weight).
fn try_load_from_dir(dir: &str, name: &str) -> Option<FontFamily> {
    if let Ok(f) = fonts::from_files(dir, name, None) {
        return Some(f);
    }
    // Fallback: single Regular file used for all variants.
    let regular_path = format!("{}/{}-Regular.ttf", dir, name);
    let data = genpdf::fonts::FontData::load(&regular_path, None).ok()?;
    Some(genpdf::fonts::FontFamily {
        regular: data.clone(),
        bold: data.clone(),
        italic: data.clone(),
        bold_italic: data,
    })
}

fn load_font(font_dir: Option<&str>, font_name: Option<&str>) -> Result<FontFamily> {
    // Names to try: explicit --font-name first, then built-in defaults.
    let names: Vec<&str> = match font_name {
        Some(n) => vec![n],
        None => FONT_NAMES.to_vec(),
    };

    if let Some(dir) = font_dir {
        // Probe only the user-supplied directory.
        for &name in &names {
            if let Some(f) = try_load_from_dir(dir, name) {
                return Ok(f);
            }
        }
        return Err(anyhow!(
            "Font '{}' not found in '{}'. \
             Expected at least '{}/{}-Regular.ttf'.",
            names.join("' or '"),
            dir,
            dir,
            names[0],
        ));
    }

    // Probe user then system directories.
    let mut tried = Vec::new();
    for dir in candidate_dirs() {
        for &name in &names {
            if let Some(f) = try_load_from_dir(&dir, name) {
                return Ok(f);
            }
            tried.push(format!("  {}/{}-Regular.ttf", dir, name));
        }
    }
    Err(anyhow!(
        "No supported monospace font found. Tried:\n{}\n\
         Install liberation-fonts or noto-fonts, or pass --font-dir DIR and/or --font-name NAME.",
        tried.join("\n")
    ))
}

/// Render a `HardCopy` to PDF bytes.
///
/// Document layout:
///   - Title page header (tool name, date, SHA-256 checksum)
///   - One section per plugin: mnemonic word blocks typeset in monospace
///   - QR code section: each chunk rendered as an embedded image
///   - Checksum footer on the final page
pub fn render(
    hardcopy: &HardCopy,
    checksum: &str,
    font_dir: Option<&str>,
    font_name: Option<&str>,
) -> Result<Vec<u8>> {
    let version = env!("CARGO_PKG_VERSION");
    let date = chrono::Local::now().format("%Y-%m-%d").to_string();

    let font_family = load_font(font_dir, font_name)?;

    let mut doc = Document::new(font_family);
    doc.set_title(format!("hardcopy v{}", version));
    doc.set_minimal_conformance();
    doc.set_line_spacing(1.25);

    let mut decorator = SimplePageDecorator::new();
    decorator.set_margins(10);
    doc.set_page_decorator(decorator);

    // Header
    doc.push(
        Paragraph::new(format!("hardcopy v{}", version))
            .styled(Style::new().bold().with_font_size(14)),
    );
    doc.push(Text::new(format!("Date:     {}", date)));
    doc.push(Text::new(format!("SHA-256:  {}", checksum)));
    doc.push(Break::new(1));

    // Track position within each QR page (0 = first slot, 1 = second slot).
    // Two QR codes share a page; a new page starts before every odd-numbered code.
    let mut qr_slot = 0usize;

    for section in &hardcopy.sections {
        match &section.content {
            HardCopySectionContent::Words(lines) => {
                doc.push(
                    Paragraph::new(section.name.clone())
                        .styled(Style::new().bold().with_font_size(11)),
                );
                doc.push(Break::new(0.5));
                for line in lines {
                    doc.push(Text::new(line.clone()));
                }
                doc.push(Break::new(1));
            }
            HardCopySectionContent::Bytes(png) => {
                if qr_slot == 0 {
                    doc.push(PageBreak::new());
                } else {
                    doc.push(Break::new(2));
                }
                doc.push(
                    Paragraph::new(section.name.clone())
                        .styled(Style::new().bold().with_font_size(11)),
                );
                doc.push(Break::new(0.5));
                let img = image::load_from_memory(png).context("Failed to decode QR code PNG")?;
                let element = Image::from_dynamic_image(DynamicImage::ImageLuma8(img.into_luma8()))
                    .context("Failed to create PDF image element")?
                    .with_alignment(genpdf::Alignment::Center);
                doc.push(element);
                qr_slot = (qr_slot + 1) % 2;
            }
        }
    }

    // Footer checksum
    doc.push(Break::new(1));
    doc.push(Text::new(format!("SHA-256:  {}", checksum)));

    let mut buf: Vec<u8> = Vec::new();
    doc.render(&mut buf).context("Failed to render PDF")?;
    Ok(buf)
}