#!/usr/bin/env bash

# GnuPG 2.2+ required for new non-interactive commands

# Generates a keyset. Note that with RSA, different keys should be used to sign/authenticate/certify vs encrypt.
# https://crypto.stackexchange.com/questions/12090/using-the-same-rsa-keypair-to-sign-and-encrypt
# See also https://security.stackexchange.com/questions/31594/what-is-a-good-general-purpose-gnupg-key-setup

# Suggested usage
# Move subkeys to 2 yubikeys (from a backup gnupghome) and primary key to safe.
# See install-naggie.sh for how to set up a new PC to work with the Yubikeys --
# note that running
#    gpg2 --card-status
# will bind one (and only one) yubikey to your installation.


if [ "$(ls)" ]; then
    echo "Must run in empty directory"
    exit 1
fi

NAME=$(git config --get user.name)
EMAIL=$(git config --get user.email)

echo "Name: $NAME"
echo "Email: $EMAIL"
read -s -p "Passphrase: " PASSPHRASE
echo

# master key
export GNUPGHOME="$(pwd)/gnupghome"
mkdir $GNUPGHOME
chmod 0700 $GNUPGHOME
cat <<EOF | gpg2 --batch --generate-key
    Key-Type: RSA
    Key-Length: 4096
    Key-Usage: cert,sign
    Expire-Date: 20320101T000000
    Name-Real: $NAME
    # Name-Comment: something
    Name-Email: $EMAIL
    Passphrase: $PASSPHRASE
    %commit
EOF


FINGERPRINT=$(gpg2 --list-key $EMAIL | grep -oE '[A-Z0-9]{40}')

# subkeys
echo "$PASSPHRASE" | gpg2 --pinentry-mode loopback --batch --no-tty --yes --passphrase-fd 0 --quick-add-key $FINGERPRINT rsa4096 encrypt 20300101T000000
echo "$PASSPHRASE" | gpg2 --pinentry-mode loopback --batch --no-tty --yes --passphrase-fd 0 --quick-add-key $FINGERPRINT rsa4096 sign 20300101T000000
echo "$PASSPHRASE" | gpg2 --pinentry-mode loopback --batch --no-tty --yes --passphrase-fd 0 --quick-add-key $FINGERPRINT rsa4096 auth 20300101T000000

gpg2 --list-keys
tar -C $GNUPGHOME --exclude='S.*' -cf gnupghome.tar .

gpg2 --export --armor > gpg-pubkeys.asc
gpg2 --export-ssh-key $EMAIL > ssh-pubkey.txt
echo $FINGERPRINT > gpg-fingerprint.txt
echo $FINGERPRINT | tail -c 17 > gpg-keyid.txt # includes /n -- (long) key id is last 16 chara
echo "$PASSPHRASE" | gpg2 --no-tty --yes --passphrase-fd 0 --export-secret-key --armor --batch --pinentry-mode loopback $EMAIL > gpg-privkeys.asc
