#!/bin/bash

USER=jryland
SERVER=http://gitbucket.localdomain
DESTINATION="${USER}@invertedlogic.com:/home/${USER}/backups/"

# Save encryption keys for later decryption (keys are encrypted, will prompt)
# if [ ! -f "${USER}-gpg2-secret.key.gpg" ]
# then
#   gpg2 -a --export-secret-keys ${USER}@xiaofrog.com > "${USER}-gpg2-secret.key"
#   gpg2 --symmetric jryland-gpg2-secret.key
# fi
# if [ ! -f "${USER}-gpg2-ownertrust.txt" ]
# then
#   gpg2 --export-ownertrust > "${USER}-gpg2-ownertrust.txt"
# fi

# Import the keys needed for decryption
# gpg2 --batch --import "${USER}-gpg2-secret.key"
# gpg2 --batch --import-ownertrust "${USER}-gpg2-ownertrust.txt"

# Save to server
rsync -v "README.md" "${DESTINATION}"
rsync -v "restore.sh" "${DESTINATION}"
rsync -v "${USER}-gpg2-secret.key.gpg" "${DESTINATION}"
rsync -v "${USER}-gpg2-ownertrust.txt" "${DESTINATION}"


# Get list of repos
curl -s "${SERVER}/api/v3/users/${USER}/repos" | jq -r '.[] | .name' | while read REPO
do
  # Copy and compress up the repo
  echo "Backing up $REPO"
  git clone --mirror "${SERVER}/git/${USER}/${REPO}.git"
  cd "${REPO}.git"
  git bundle create "../${REPO}.git.bundle" --all
  cd ..

  # Encrypt and copy to destination
  echo "Encrypting backup of $REPO"
  gpg2 --yes -er "${USER}" "${REPO}.git.bundle"
  rsync -v "${REPO}.git.bundle.gpg" "${DESTINATION}"

  # Cleanup any temporary files created
  rm -rf "${REPO}.git" "${REPO}.git.bundle" "${REPO}.git.bundle.gpg"
done


