#!/bin/bash

# Usage: downloader.sh username teamname
USER=${1}

if [ -d "$USER" ]
then
    echo "User folder already exists"
    exit 1
fi

mkdir "$USER"
cd $USER

i=1
NEXT_URL="https://api.bitbucket.org/2.0/repositories/${USER}?pagelen=100&role=member"
while [ $NEXT_URL != null  ]
do
    curl -u $USER $NEXT_URL > repoinfo"$i".json
    jq -r '.values[] | .links.clone[1].href' repoinfo"$i".json >> repos.txt
    i=$((i++))
    NEXT_URL=`jq -r '.next' repoinfo"$i".json`
done

exit 0

for repo in `cat repos.txt`
do
    echo "Cloning" $repo
    if echo "$repo" | grep -q ".git"; then
        command="git"
    else
        command="hg"
    fi
    $command clone $repo
done

cd ..
