#!/bin/bash

exitCode=0
exitCode=$(mktemp) && echo 0 >$exitCode

handleRepo() {
    read repo url branchName
    if  [ ! -d "$repo" ] || [ ! "$(ls -A $repo)" ] ; then
        #clone if the local working copy does not exist (or empty)
        printf "\n===== repo:$repo ---->  cloning "$repo" at "$url" for branch: "$branchName"\n"
        git clone $url -b $branchName
    else
        #get current branch
        cd $repo
        currentBranch=$(git symbolic-ref HEAD | sed -e 's/refs\/heads\///g')
        printf "\n===== repo:$repo ----> current branch = '$currentBranch'\n"

        if [[ $currentBranch == $branchName ]]; then
            printf "\n===== repo:$repo ----> pulling branch: $branchName \n"
            git pull
        else
            git fetch -a
            #checkout the brach if the folder is already downloaded
            printf "\n===== repo:$repo ----> checkout "$repo" at branch: "$branchName"\n"
            git checkout $branchName
            if [[ $? == 0 ]]; then
                git pull
            else
                echo "error: branch $branchName does not exist, exit code = 1"
                echo 1 >$exitCode
                exit 1
            fi
        fi
        cd ..
    fi
    printf "\n===== repo:$repo ----> git operation finished"
}

file="dependency.txt"
grep -vE '^(\s*$|#)' $file | (while read -r line
do echo $line | handleRepo & done
wait
echo "exitCode => $(cat $exitCode)"
exit $(cat $exitCode))
