#!/bin/bash

url=$1
location=$2
user=$3
password=$4
token=$5
cli=$6
sha=$7
name=$8

# If there are credentials
# Replace '@' by its hexa character to clean the fields to avoid confusion with the '@' delimiter 
if [ $user != "None" ] && [ $password != "None" ]; then
    cleaned_user=`echo $user | sed 's/@/%40/g'`
    cleaned_password=`echo $password | sed 's/@/%40/g'`
    credentials="${cleaned_user}:${cleaned_password}@"
else
  if [ $token != "None" ];then
    credentials="oauth2:${token}@"
  else
    credentials=""
  fi
fi

http=`echo $url | cut -d '/' -f1`
git=`echo $url | cut -d '/' -f3`
end=`echo $url | cut -d '/' -f4-`
url="${http}//${credentials}${git}/${end}"

# If there is a location
if [ $location != "None" ];then
  cd $location
fi

git clone --recursive $url $name

if [ $? -eq 0 ];then
  # If sha or tag is specified
  if [ $sha != "None" ];then
    cd $name
    git checkout $sha || exit 1
    cd ..
  fi
  # If the system has to be installed
  if [ $cli == "True" ];then
    cd $name

    diva_evaluation_cli/bin/install.sh
  fi
fi
