#!/bin/bash
#
# Copyright © 2021-2025 by Friends Of OpenPGP organization <info@foopgp.org>.
#          All Right Reserved
#
# Scan QRcodes containing parts of OpenPGP secrets from IMAGES or webcam,
# and import this secrets into a factory reseted OpenPGP secured device (eg yubikey).
#

PGPI_NAME="$(basename $(readlink -f "$BASH_SOURCE") )"
PGPI_VERSION="0.0.7"

### Default option values ###

set -e
LOGEXITPRIO=crit
LOGLEVEL=6

usage="Usage: $BASH_SOURCE [OPTIONS]... [--] [IMAGES]...

$PGPI_NAME scan QRcodes containing parts of OpenPGP secrets from IMAGES or webcam,
and import this secrets into a factory reseted OpenPGP secured device (eg yubikey)."

soptions="
  -k, --no-send            don't send public key (certificate) to HKPS keyserver ($HKPSSERVER)
  -v, --verbose            increase log verbosity: ...<notice[5]<info[6]<debug[7]  (current: $LOGLEVEL)
  -q, --quiet              decrease log verbosity: ...<err[3]<warning[4]<notice[5]<...  (current: $LOGLEVEL)
  -h, --help               show this help and exit
  -V, --version            show version and exit"


### Handling options ###

helpmsg="$usage

Options: $soptions
"

nosend=""

for ((i=0;$#;)) ; do
case "$1" in
    -k|--no-send) nosend="--no-send" ;;
	-l|--log-l*) shift ; LOGLEVEL="$1" ; [[ "$LOGLEVEL" == [0-9] ]] || { echo -e "Error: log-level out of range [0-7]" >&2 ; exit 2 ; } ;;
	-L|--log-e*) shift ; LOGEXITPRIO="$1"
		grep -q "\<$LOGEXITPRIO\>" <<<${!loglevels[@]} || { echo -e "Error: log-exit \"$LOGEXITPRIO\" is none of: ${!loglevels[@]}" >&2 ; exit 2 ; } ;;
	-v|--verb*) ((LOGLEVEL++)) ;;
	-q|--quiet) ((LOGLEVEL--)) ;;
	-h|--h*) echo "$helpmsg" ; exit ;;
	-V|--vers*) echo "$PGPI_NAME $PGPI_VERSION" ; exit ;;
	--) shift ; break ;;
	-*) echo -e "Error: Unrecognized option $1\n$helpmsg" >&2 ; exit 2 ;;
	*) break ;;
esac
shift
done

### functions ###

. "$(dirname "$BASH_SOURCE")"/bl-log --no-act --log-level "$LOGLEVEL" --log-exit "$LOGEXITPRIO"
. "$(dirname "$BASH_SOURCE")"/bl-interactive --
. "$(dirname "$BASH_SOURCE")"/bl-security --
. "$(dirname "$BASH_SOURCE")"/bl-qrkey --

### Init ###

_pgpid_qrscan_onexit() {
	[[ -d "$TMPDIR" ]] && bl_shred_path -v -f -r "$TMPDIR" 2> >(bl_log warning) | bl_log debug
}

TMPDIR=$(mktemp -d -t "$PGPI_NAME".XXXXXX) || log crit "crit: Can not create a safe temporary directory."

trap _pgpid_qrscan_onexit EXIT

mkdir -p "$TMPDIR/gnupg"
chmod -R go-rwx "$TMPDIR"

### Run ###

# Force restart gpg-agent
gpgconf --kill gpg-agent

FPR=$(bl_qrkey_scan --workdir "$TMPDIR" --homedir "$TMPDIR/gnupg" "$@")

while ! gpg --homedir "$TMPDIR/gnupg" --card-status > >(bl_log debug) 2> >(bl_log notice) ; do
	sleep 1
	bl_msgstop "Please plug an OpenPGP card or dongle..."
done

if [[ -f "$TMPDIR/passphrase" ]] ; then
	bl_qrkey_totoken --homedir "$TMPDIR/gnupg" $nosend --passfrom "$TMPDIR/passphrase" "$FPR"
else
	bl_qrkey_totoken --homedir "$TMPDIR/gnupg" $nosend "$FPR"
fi

