softcopy 1.0.0

Sibling project to 'hardcopy'; used to convert back into keys/certs/etc.
Documentation
/// Simple CLI for validating and generating a soft-copy from user-input.
///
/// It is assumed that the user-input is provided as read from the
/// hard-copy as generated by the sibling program `hardcopy`. If not this
/// may be more difficult to follow the instructions this program provides
/// however, the validation of the soft-copy may still be possible.
///
#[macro_use]
extern crate clap;
use clap::{App, AppSettings, ArgMatches};

use anyhow::{anyhow, bail, Result};
use softcopy::*;

use std::io::{BufRead, Write};

use libhardcopy::plugins::bip39::{Bip39Plugin, BIP39_INSTRUCTIONS};
use libhardcopy::plugins::diceware::{DicewarePlugin, DICEWARE_INSTRUCTIONS};
use libhardcopy::plugins::pgpfone::{PGPfonePlugin, PGPFONE_INSTRUCTIONS};
use libhardcopy::plugins::skeyotp::{SKeyOtpPlugin, SKEY_OTP_INSTRUCTIONS};
use libhardcopy::plugins::SoftCopyGenerator;
use libhardcopy::HardCopyInput;

use sha2::{Digest, Sha256};

static APP_NAME: &str = "softcopy";

fn args() -> ArgMatches<'static> {
    App::new(APP_NAME)
        .about(crate_description!())
        .version(crate_version!())
        .version_short("v")
        .setting(AppSettings::ColoredHelp)
        .setting(AppSettings::DontCollapseArgsInUsage)
        .args(configs().as_slice())
        .get_matches()
}

fn main() -> Result<()> {
    let _ = pretty_env_logger::init();
    let config: SoftCopyConfig = args().into();
    log::set_max_level(config.get_log_level());

    if config.verify {
        run_verify(&config)
    } else {
        run_decode(&config)
    }
}

fn run_decode(config: &SoftCopyConfig) -> Result<()> {
    let output_path = config
        .output
        .as_deref()
        .or(config.file.as_deref())
        .ok_or_else(|| {
            anyhow!("Output file required: use -o FILE or provide FILE as a positional argument.")
        })?;

    let plugin_name = config.plugin.as_deref().unwrap_or("plugins.pgpfone");
    let (instructions, words_per_line): (&str, usize) = match plugin_name {
        "plugins.pgpfone"  => (PGPFONE_INSTRUCTIONS, 4),
        "plugins.skeyotp"  => (SKEY_OTP_INSTRUCTIONS, 6),
        "plugins.bip39"    => (BIP39_INSTRUCTIONS, 6),
        "plugins.diceware" => (DICEWARE_INSTRUCTIONS, 6),
        other => bail!(
            "Unknown plugin: '{}'. Supported: plugins.pgpfone, plugins.skeyotp, plugins.bip39, plugins.diceware",
            other
        ),
    };

    println!("{}", instructions);
    println!("Enter the mnemonic words from your hard-copy, one line at a time.");
    println!(
        "Each line should have {} words (optionally prefixed with the line number).",
        words_per_line
    );
    println!("Press Enter on an empty line or Ctrl+D when finished.\n");

    let mut hard_input = HardCopyInput::new();
    let stdin = std::io::stdin();
    let mut line_num = 1usize;

    loop {
        print!("Line {:04} > ", line_num);
        std::io::stdout().flush()?;

        let mut line = String::new();
        let n = stdin.lock().read_line(&mut line)?;

        if n == 0 || line.trim().is_empty() {
            break;
        }

        hard_input.push_line(line.trim());
        line_num += 1;
    }

    if hard_input.words().is_empty() {
        bail!("No words were entered. Nothing to decode.");
    }

    let softcopy = match plugin_name {
        "plugins.skeyotp" => SKeyOtpPlugin
            .generate_soft_copy(&mut hard_input)
            .map_err(|_| anyhow!("Decoding failed"))?,
        "plugins.bip39" => Bip39Plugin
            .generate_soft_copy(&mut hard_input)
            .map_err(|_| anyhow!("Decoding failed"))?,
        "plugins.diceware" => DicewarePlugin
            .generate_soft_copy(&mut hard_input)
            .map_err(|_| anyhow!("Decoding failed"))?,
        _ => PGPfonePlugin
            .generate_soft_copy(&mut hard_input)
            .map_err(|_| anyhow!("Decoding failed"))?,
    };

    std::fs::write(output_path, &softcopy.bytes)?;
    println!(
        "\nWritten {} bytes to: {}",
        softcopy.bytes.len(),
        output_path
    );

    Ok(())
}

fn run_verify(config: &SoftCopyConfig) -> Result<()> {
    let file_path = config
        .file
        .as_deref()
        .or(config.output.as_deref())
        .ok_or_else(|| anyhow!("File to verify required: softcopy --verify FILE"))?;

    let data =
        std::fs::read(file_path).map_err(|e| anyhow!("Failed to read '{}': {}", file_path, e))?;

    let actual = hex::encode(Sha256::digest(&data));

    print!("Please enter the SHA-256 checksum from your hard-copy:\n> ");
    std::io::stdout().flush()?;

    let mut expected = String::new();
    std::io::stdin().lock().read_line(&mut expected)?;
    let expected = expected.trim();

    if actual.eq_ignore_ascii_case(expected) {
        println!("Checksum matches. Data integrity verified.");
        Ok(())
    } else {
        println!("Checksum MISMATCH.");
        println!("  Expected: {}", expected);
        println!("  Actual:   {}", actual);
        bail!("Verification failed: checksums do not match.")
    }
}