#!/bin/bash
export GITROOT=${GITROOT:=https://gitlab.cern.ch/atlas-tdaq-software}

CHECKOUT_AREA=${CHECKOUT_AREA:=$(pwd)}

usage()
{
  echo " usage: $0 [--here] [--jobs=<N>] [--package-file=<path>] [--packages=<pkg-list> ] [--variant=<name>] <project> [ <version> ]"
  echo
  echo "  If <version> is missing, -99-00-00 is appended to the <project> name."
  echo
  echo "  Current settings: "
  echo "    GITROOT=${GITROOT}"
  echo "    CHECKOUT_AREA=${CHECKOUT_AREA}"
}

while [ $# -gt 0 ]; do
    case $1 in
        --here)
            CHECKOUT_AREA=`pwd`
            shift
            ;;
        --jobs=*)
            JOBS=" -j ${1#--jobs=} "
            shift
            ;;
        --package-file=*)
            TDAQ_PACKAGES_FILE="${1#--package-file=}"
            shift
            ;;
        --packages=*)
            TDAQ_PACKAGES="${1#--packages=}"
            shift
            ;;
        --variant=*)
            TDAQ_PACKAGES_FILE="cmake/variants/${1#--variant=}/packages.txt"
            shift
            ;;
        --help|-h)
            usage
            exit 0
            ;;
        -*)
            echo "Unknown option: $1"
            exit 1
            ;;
        *)
            break
            ;;
    esac
done

if [ $# -lt 1 ]; then
  usage
  exit 1
fi

project=$1
shift

if [ $# -lt 1 ]; then
  version=${project}-99-00-00
else
  version=$1
fi

cd ${CHECKOUT_AREA} || exit 2

mkdir -p ${project} || exit 3 
cd ${project} || exit 4 

# hack to handle CentOS 7 ancient git version which does not support 
# git submodule update --depth <n> ...
#
update_options="--depth 1"
git_v=$(git version | awk '{ print $3; }' | cut -d. -f1)
[ ${git_v} -lt 2 ] && update_options=""

if [ ! -d ${version}/.git ]; then
    if [ -z "${TDAQ_PACKAGES}" -a -z "${TDAQ_PACKAGES_FILE}" ]; then
        # get initial top level setup from branch
        # note that destination dir may exist here if it's empty
        git clone -q --depth 1 ${CLONE_OPTIONS} ${JOBS} -b ${version} ${GITROOT}/${project}-cmake.git ${version} || exit 4
        (cd ${version}; git submodule -q update ${update_options} ${CLONE_OPTIONS} -i)
    else
        git clone -q --depth 1 ${CLONE_OPTIONS} -b ${version} ${GITROOT}/${project}-cmake.git ${version}
        # This allows TDAQ_PACKAGE_FILE to be relative to the project root, e.g. ./cmake/HLT-packages.txt
        if [ -n "${TDAQ_PACKAGES_FILE}" ]; then
            if [ -f "${TDAQ_PACKAGES_FILE}" ]; then
                TDAQ_PACKAGES=$(cat ${TDAQ_PACKAGES_FILE})
            elif [ -f "${version}/${TDAQ_PACKAGES_FILE}" ]; then
                TDAQ_PACKAGES=$(cat ${version}/${TDAQ_PACKAGES_FILE})
            fi
        fi
        (cd ${version}; git submodule -q update ${update_options} -i ${TDAQ_PACKAGES})
    fi
else
   # update top level setup
   (cd ${version}; git checkout -q ${version} && git pull -q  && git submodule -q update ${update_options} ${CLONE_OPTIONS})
fi
