#!/bin/bash

# Usage: getpkg [-l][-s] package-name [[-b] tag]
# 
# Checks out a requested version of a package in the current directory, creating version directory as needed to CMT.
#
# Takes the following environment:
#
# GITROOT, "https://:@gitlab.cern.ch:8443/atlas-tdaq-software/" Kerberos authentication is used as default
#
# Andrei.Kazarov,	Apr. 2002
# Last modified:	Apr. 2003

GITGROUP=${GITGROUP:="atlas-tdaq-software"}
GITROOT=${GITROOT:="https://:@gitlab.cern.ch:8443/${GITGROUP}/"} ; export GITROOT

if [ $# -eq 0 -o "${1}" == "-h" ]; then
echo "Usage: getpkg [-l][-s] <package> [[-b] tag] "  
echo " Checks-out a package <package> from GIT LAB in the current directory as <cwd>/<package>."
echo " Uses GITROOT as URL to GIT LAB, defaults to Kerberos access as https://:@gitlab.cern.ch:8443/${REPO}/"
echo " -b specifies the branch to check-out."
echo " -l lists all tags in the repository."
echo " -s shallow checkout with --depth 1."
echo " If [tag] or branch is not specified, checks-out master branch."
echo " NB: Checking out a tag does not create a branch, so you can not commit back your changes: checkout a branch or create a branch from a tag!"
exit 0 ;
fi

while [ $# -gt 0 ]
do
  case "$1" in
    -l)
        git ls-remote --tags $GITROOT/${2}.git | grep -v '\^{}$' | sed 's/^.*tags\///'
        exit 0
        ;;
    -s)
        flags="--depth 1"
        shift
        ;;
    *)
        break
        ;;
  esac
done

package=$1
tag=$2
dirname=$1

[ -d $dirname ] && { echo "Directory $dirname aready exist, please remove it first."; exit 1; }

if [ -z "${tag}" ]; then
    git clone -q ${flags} $GITROOT/${package}.git || { echo "Failed to clone git repo."; exit 1 ; }
    cd ${package}
elif [ "${tag}" = "-b" ]; then
    tag=$3
    git clone -q ${flags} -b ${tag} $GITROOT/${package}.git || { echo "Failed to clone git repo."; exit 1 ; }
    cd ${package}
else
    git clone -q ${flags} -b ${tag} $GITROOT/${package}.git || { echo "Failed to clone git repo."; exit 1 ; }
fi

exit 0
