Skip to content

Take backup of your BitBucket repositories using Shell script

#!/bin/bash

#usage() { echo "Usage: $0 -k <app key> -u <app user> -w <workspace> [-t <target directory>] [-p <project>]" 1>&2; exit 1; }

TARGET_DIR="."
APP_USER='itadmin-poopcode'
APP_KEY='5b5afa9jBuXqPwpNf54d'
WORKSPACE='PoopcodeWorkspace'

apt-get install jq -y

apt-get install zip -y

if [ -z "${TARGET_DIR}" ] || [ -z "${APP_KEY}" ] || [ -z "${APP_USER}" ] || [ -z "${WORKSPACE}" ]; then
  usage
fi

rm -rf "codebase"

rm -rf "codebase.zip"

mkdir codebase

cd "codebase" || exit

BASE_URL="https://api.bitbucket.org/2.0/repositories/${WORKSPACE}"
NEXT_URL=${BASE_URL}
AUTH="Authorization: Basic $(echo -n "${APP_USER}:${APP_KEY}" | base64)"

while : ; do
    printf "get repositories from %s ...\n" "${NEXT_URL}"
    REPOSITORIES=$(curl --silent --location --request GET "${NEXT_URL}" --header "${AUTH}")
    NEXT_URL=$(echo "${REPOSITORIES}" | jq -r ".next")

    readarray -t VALUES < <(echo "${REPOSITORIES}" |  jq -c '.values[]')
    for item in "${VALUES[@]}"; do
      REPO_NAME=$(jq -r '.name' <<< "$item")
      REPO_PROJECT=$(jq -r '.project.name' <<< "$item")

      if [ -z "${PROJECT}" ] || [ "${REPO_PROJECT}" == "${PROJECT}" ] ; then

        REPO_URL=$(jq -r '.links.clone[0].href' <<< "$item")
            #REPO_URL="$(REPO_URL//@/:$APP_KEY@/)"
            #REPO_URL=$(echo "$REPO_URL" | tr '@' ':"$APP_KEY"@')
            #REPO_URL = $(sed "s/@/:$APP_KEY@/" <<< "$REPO_URL")
            #REPO_URL=$(tr '@' ':$APP_KEY@' <<<"$REPO_URL")
            REPO_URL=$(echo $REPO_URL | sed -e "s/@/:$APP_KEY@/g")
            printf "Getting repo URL"
            printf "${REPO_URL}"
        REPO_DIR=$(echo "${REPO_URL}" | sed 's%^.*/\([^/]*\)\.git$%\1%g')

        if [ ! -d "${REPO_DIR}" ]; then
          printf "clone %s/%s ...\n"  "${REPO_PROJECT}" "${REPO_NAME}"
              printf "${REPO_URL}"
          git clone --mirror "${REPO_URL}"
              cd "${REPO_DIR}".git
              git bundle create ../${REPO_DIR}.bundle --all
              cd ..
              rm -rf "${REPO_DIR}".git
        else
          printf "remote update %s/%s\n"  "${REPO_PROJECT}" "${REPO_NAME}"
          cd "${REPO_DIR}" || return
          git remote update
          cd ..
        fi

      else
        printf "skip %s/%s\n"  "${REPO_PROJECT}" "${REPO_NAME}"
      fi
    done
      break
    [[ ${NEXT_URL} != "null" ]] || break
      
done

FILE_NAME="code_base"
ZIP_FILE_NAME=$FILE_NAME.'echo $(date "+%Y.%m.%d-%H.%M.%S")'

cd ".."

printf "Deleting node_modules folder"

find -type d -name 'node_modules*' -exec rm -rv {} +
      
printf "Zipping code"

#zip -r codebase.zip "codebase"

tar -zcvf codebase.tar.gz codebase/

ls -a
      
printf "Zip done."

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.