use std::{
io::{self, IsTerminal},
num::NonZero,
};
use anyhow::{Context, anyhow};
use clap::{ArgAction, Parser, ValueEnum};
use fancy_regex::Regex;
use fingerprunk::Fingerprunk;
use sequoia_openpgp::packet::UserID;
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
#[arg(short, long)]
regex: Regex,
#[arg(long, value_enum, default_value_t)]
status: StatusEnabled,
#[arg(short = 'n', long, value_name = "NUM")]
count: Option<NonZero<u64>>,
#[arg(short, long, action = ArgAction::SetTrue)]
password: bool,
#[arg(short, long = "userid")]
userid: Vec<UserID>,
#[arg(long, conflicts_with = "userid", action = ArgAction::SetTrue)]
no_userid: bool,
#[arg(long, value_name = "NUM")]
workers: Option<NonZero<usize>>,
}
#[derive(ValueEnum, Clone, Copy, Debug, Default)]
enum StatusEnabled {
#[default]
Auto,
Always,
Never,
}
impl StatusEnabled {
fn evaluate(self) -> bool {
match self {
Self::Auto => io::stderr().is_terminal() && !io::stdout().is_terminal(),
Self::Always => true,
Self::Never => false,
}
}
}
fn main() -> anyhow::Result<()> {
let args = Args::parse();
let workers = match args.workers {
Some(workers) => workers,
None => std::thread::available_parallelism().context(
"unable to determine available parallelism, \
use `--workers <NUM>` to specify amount of worker threads",
)?,
};
if !args.no_userid && args.userid.is_empty() {
eprintln!(
"WARNING: No user ID was provided.\n\
You may experience problems importing generated keys into GnuPG.\n\
Use `--userid <USERID>` to add a user ID.\n"
);
}
let password = if args.password {
let password = rpassword::prompt_password(
"Enter password for encrypting found keys (leave empty for no encryption): ",
)
.context("Failed to prompt password")?;
if password.is_empty() {
None
} else {
let password_retype = rpassword::prompt_password("Retype password: ")
.context("Failed to prompt password retype")?;
if password_retype == password {
Some(password.into())
} else {
return Err(anyhow!("Passwords do not match"));
}
}
} else {
None
};
let config = fingerprunk::Config {
regex: args.regex,
status_enabled: args.status.evaluate(),
count: args.count,
password,
userids: args.userid,
workers,
};
Fingerprunk::new_from_config(config).run()
}