#!/bin/bash

BACKUP_USER=jryland

echo "*********************************"
echo "*********   IMPORTANT   *********"
echo "*********************************"
echo "This will change your ~/.gnupg directory, however it will"
echo "make a backup to ~/.gnupg-bak. Do you still want to proceed?"
echo "Press enter to continue or Ctrl-C to cancel"
read

if [ -d ~/.gnupg-bak ]
then
    echo "Backup of ~/.gnupg directory already exists, bailing out"
    exit
fi
if [ -d ~/.gnupg ]
then
    mv ~/.gnupg ~/.gnupg-bak
fi
if [ -d ~/.gnupg ]
then
    echo "Still a ~/.gnupg directory exists, bailing out"
    exit
fi

if [ ! -f "${BACKUP_USER}-gpg2-secret.key.gpg" ]
then
  cat | gpg2 --verbose --batch --full-gen-key << EOF
    %echo Generating a basic OpenPGP key
    Key-Type: RSA
    Key-Length: 4096
    Subkey-Type: RSA
    Subkey-Length: 4096
    Name-Real: John Ryland
    Name-Comment: ${BACKUP_USER}
    Name-Email: jryland@xiaofrog.com
    Expire-Date: 0

EOF
  gpg2 --export-secret-keys ${BACKUP_USER} | gpg2 --symmetric --cipher-algo AES256 > ${BACKUP_USER}-gpg2-secret.key.gpg
  gpg2 --export             ${BACKUP_USER} | gpg2 --symmetric --cipher-algo AES256 > ${BACKUP_USER}-gpg2-public.key.gpg
fi

gpg2 --batch -d "${BACKUP_USER}-gpg2-public.key.gpg" | gpg2 --import
gpg2 --batch -d "${BACKUP_USER}-gpg2-secret.key.gpg" | gpg2 --import --allow-secret-key-import


