#!/bin/bash

BACKUP_USER=jryland
SOURCE="${BACKUP_USER}@invertedlogic.com:/home/${BACKUP_USER}/backups"
DESTINATION=restored

echo "*********************************"
echo "*********   IMPORTANT   *********"
echo "*********************************"
echo "Don't run this on the remote server, copy it locally first and run from a local machine"
echo "This will extract the repos to where it is run from"
echo "Press enter to continue or Ctrl-C to cancel"
read

# Copy the backups from the server
rsync -rv "${SOURCE}" "."

echo "Passphase is the password like this: 'a******5*' replacing '*' as appropriate"
echo "Press enter to continue or Ctrl-C to cancel"
read

# Import the keys needed for decryption
#gpg2 --decrypt "backups/${BACKUP_USER}-gpg2-secret.key.gpg" > "backups/${BACKUP_USER}-gpg2-secret.key"
#gpg2 --import "backups/${BACKUP_USER}-gpg2-secret.key"
#gpg2 --import-ownertrust "backups/${BACKUP_USER}-gpg2-ownertrust.txt"
gpg2 -d "backups/${BACKUP_USER}-gpg2-public.key.gpg" | gpg2 --import
gpg2 -d "backups/${BACKUP_USER}-gpg2-secret.key.gpg" | gpg2 --import --allow-secret-key-import

echo "Passphase is the password like this: 'a******5*  ' replacing '*' as appropriate with trailing spaces"
echo "Press enter to continue or Ctrl-C to cancel"
read

# For each repo backup
mkdir -p "${DESTINATION}"
for REPO_FILE in backups/*.git.bundle.gpg
do
  REPO=`basename -s .git.bundle.gpg "${REPO_FILE}"`
 
  # Decrypt the repo bundle
  echo "Decrypting backup of ${REPO}"
  gpg2 --yes -d "${REPO_FILE}" > "${REPO}.git.bundle"

  # Extract it
  echo "Restoring from backup of ${REPO}"
  cd "${DESTINATION}"
  git clone "../${REPO}.git.bundle"
  cd ..

  # Cleaning up temporary files
  rm -f "${REPO}.git.bundle"
done


echo "*************************"
echo "* Restore complete"
echo "* Files extracted to ${DESTINATION}"
echo "* Please now manually import these mirrors of the repos"
echo "*************************"

