#!/bin/bash

GITLAB_URL="https://gitlab.sig-gis.com/api/v4"
USER_NAME="sig-app"
read -s -p "Please enter your Gitlab Personal Authentication Token:"$'\n' USER_AUTH_TOKEN
HEADER="PRIVATE-TOKEN: $USER_AUTH_TOKEN"

function generate-project-access-token() {
    TARGET_REPO="$1"
    TOKEN_NAME="$2"
    PROJECT_ID=$(curl -s --header "$HEADER" "$GITLAB_URL/projects?search=$TARGET_REPO" | jq '.[0].id')
    EXPIRES=$(date '+%Y-%m-%d' -d "$(date) + 1 year - 1 day")
    PAYLOAD="{\"name\":\"$TOKEN_NAME\", \"scopes\":[\"read_api\", \"read_repository\"], \"expires_at\":\"$EXPIRES\", \"access_level\": 20 }"
    TOKEN_RESPONSE=$(curl -s --header "$HEADER" --header "Content-Type:application/json" --data "$PAYLOAD" "$GITLAB_URL/projects/$PROJECT_ID/access_tokens")
    GENERATED_TOKEN=$(echo "$TOKEN_RESPONSE" | jq -r '.token')
    echo "$GENERATED_TOKEN"
}

function install-authentication() {
    PROJECT_TOKEN="$1"
    TARGET_REPO="$2"
    git config --global credential.https://gitlab.sig-gis.com.useHttpPath true
    git config --global credential.https://gitlab.sig-gis.com.helper store
    echo "url=https://sig-app:${PROJECT_TOKEN}@gitlab.sig-gis.com/sig-gis/$TARGET_REPO.git" | git credential approve
    git clone "https://gitlab.sig-gis.com/sig-gis/$TARGET_REPO.git"
    rm -rf "$TARGET_REPO"
}

for REPO in $@; do
    TOKEN_NAME="${REPO}:${USER_NAME}@$(hostname)"
    PROJECT_TOKEN="$(generate-project-access-token $REPO $TOKEN_NAME)"
    install-authentication "$PROJECT_TOKEN" "$REPO"
done
