#!/usr/bin/env bash
# Desc: Export each pubkey to a separate file
# Usage: bk-export-min-pubkeys.sh
# Version: 0.0.2

time_now="$(date +%Y%m%dT%H%M%S%z)";
dir_out="./$time_now..pubkeys";

yell() { echo "$0: $*" >&2; } # print script path and all args to stderr
die() { yell "$*"; exit 111; } # same as yell() but non-zero exit status
try() { "$@" || die "cannot $*"; } # runs args as command, reports args if command fails
gpg_get_pubkey() {
    # Desc: Output ascii-armored gpg pubkey via stdout
    # Input: arg1: pgp long id
    # Output: stdout: ascii-armored minimal-signature pgp key
    # Example: gpg_get_pubkey 0xa0a295abdc3469c9
    # Depends: gpg  2.2.12
    local longid output;
    longid="$1";

    output="$(gpg --export --armor --export-options export-minimal "$longid")";
    echo "$output";
} # Output ascii-armored gpg pubkey via stdout
main() {
    # Create list of primary key fingerprints
    list_longid="$(gpg --list-keys | grep "^pub" | awk '{print $2}' | cut -d'/' -f2)";

    # Create output dir
    path_out="$(readlink -f "$dir_out")";
    #yell "DEBUG:path_out:$path_out";
    if [[ ! -d "$path_out" ]]; then
	mkdir -p "$path_out";
	yell "NOTICE:Creating output directory:$path_out";
    fi;

    # Iterate through list
    while read -r longid; do
	yell "STATUS:Exporting $longid";

	# Export file
	pubkey_ascii="$(try gpg_get_pubkey "$longid")";
	#yell "DEBUG:pubkey_ascii:$pubkey_ascii";
	echo "$pubkey_ascii" > "$path_out"/"$longid".asc

    done < <( echo "$list_longid" );
}; # main program

main "$@";

# Author: Steven Baltaktei Sandoval
# License: GPLv3+
