#!/bin/bash

BACKUP_USER=jryland
REPO_SERVER=http://gitbucket.localdomain

# TODO: also need to backup the gitbucket DB

mkdir -p tmp
cd tmp

# Get list of repos
curl -s "${REPO_SERVER}/api/v3/users/${BACKUP_USER}/repos" | jq -r '.[] | .name' | while read REPO
do
  # Copy and compress up the repo
  echo "Backing up $REPO"
  git clone --mirror "${REPO_SERVER}/git/${BACKUP_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 "${BACKUP_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


echo "**************************"
echo "WARNING..."
echo "Looks like clone --mirror is not fetching and backing up all branches, just master. Check it"
echo "**************************"


