#!/bin/sh

set -e

# figure out which branch we're targeting
#   CI_COMMIT_BRANCH is set when building a branch,
#   CI_COMMIT_TAG is set when building a tag, and
#   CI_MERGE_REQUEST_TARGET_BRANCH_NAME is set when building an MR.
# We check them one after the other to pick the default branch name.
readonly url="${LIDARVIEW_URL:-https://gitlab.kitware.com/LidarView/lidarview.git}"

# figure out which lidarview branch to checkout.
if [ -n "$LIDARVIEW_BRANCH" ]; then
    lv_branch="$LIDARVIEW_BRANCH"
elif [ -n "$CI_COMMIT_TAG" ]; then
    lv_branch="$CI_COMMIT_TAG"
elif [ -n "$CI_MERGE_REQUEST_TARGET_BRANCH_NAME" ]; then
    lv_branch="$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"
elif [ -n "$CI_COMMIT_BRANCH" ]; then
    lv_branch="$CI_COMMIT_BRANCH"
else
    lv_branch="master"
fi
readonly lv_branch

# The CentOS 7 containers have an old git that does not support this flag
# (added in 2.9.0).
shallow_submodules="--shallow-submodules"
if echo "$CI_JOB_NAME" | grep -q "linux.*:build"; then
    shallow_submodules=""
fi
readonly shallow_submodules

lv_repository="$CI_PROJECT_DIR/source-lidarview"

echo "$ git clone --recursive $shallow_submodules -b \"$lv_branch\" \"$url\""

# full clone of lidarview with shallow-submodule. full clone needed so that `git describe` works correctly
GIT_LFS_SKIP_SMUDGE=1 git clone --recursive $shallow_submodules -b "$lv_branch" "$url" "$lv_repository"

# let's print lidarview version for reference even when the artifacts disappear
cd $lv_repository
git describe
# git -C "$lv_repository" describe

# checkout to specific LVCore branch if needed
if [ -n "$LVCORE_BRANCH" ]; then
    cd LVCore && git checkout "$LVCORE_BRANCH"
fi
