#!/bin/bash

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

if [ -d "$TEAM" ]
then
    echo "Team folder already exists"
    exit 1
fi

mkdir "$TEAM"
cd $TEAM

i=1
NEXT_URL="https://api.bitbucket.org/2.0/repositories/${TEAM}?pagelen=100"

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

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 ..
