#!/bin/bash

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

# 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 the system has to be installed
  if [ $cli == "True" ];then
    repo_name=`echo $url | rev | cut -d '.' -f2 | rev`
    repo_name=`echo $repo_name | rev | cut -d '/' -f1 | rev`
    cd $repo_name

    diva_evaluation_cli/bin/install.sh
  fi
fi
