#!/bin/bash
# Usage: list_tags <project> [ <pattern> ]

GITROOT=${GITROOT:=https://:@gitlab.cern.ch:8443/atlas-tdaq-software}
GITAPI=${GITAPI:=https://gitlab.cern.ch/api/v4}

GITTOKEN_FILE=${GITTOKEN_FILE:=${HOME}/private/git_token}
GITTOKEN=${GITTOKEN:=$(cat ${GITTOKEN_FILE})}

if [ $# -eq 0 ]; then
    echo "Usage: $0 <project> [ <pattern> ]"
    echo "    where <project> is a valid versioned project name, e.g. tdaq-06-02-00"
    echo "    and <pattern> a regular expression to filter the output"
    exit 1
fi

release="$1"
pattern="$2"

[ -z "${pattern}" ] && pattern=".*"

case $release in
    tdaq-common-*)
	project=tdaq-common-cmake
	;;
    dqm-common-*)
        project=dqm-common-cmake
	;;
    *)
        project=tdaq-cmake
        ;;
esac

case ${release} in
    *-nightly)
        branch=$(echo ${release} | sed 's;nightly;99-00-00;')
        ;;
    *-dev)
        branch=$(echo ${release} | sed 's;dev;99-00-01;')
        ;;
    nightly)
        branch=tdaq-99-00-00
        ;;
    dev)
        branch=tdaq-99-00-01
        ;;
    *)
        branch=${release}
        ;;
esac

tc=$(mktemp -d)
trap "rm -rf ${tc}" EXIT

# Get the URLs for the submodules
curl -s --request GET --header "PRIVATE-TOKEN: ${GITTOKEN}" \
    -F ref=${branch} \
    ${GITAPI}/projects/atlas-tdaq-software%2F${project}/repository/files/.gitmodules | python -c 'from __future__ import print_function;import base64,sys,json; s = json.load(sys.stdin); print(base64.b64decode(s["content"]).decode("utf-8"))' > ${tc}/.gitmodules 2> /dev/null

if [ $? -ne 0 ]; then
    echo "Cannot get submodule info, maybe invalid branch: ${branch} ?"
    exit 1
fi

page=1
while true
do
    # Get the submodule refs
    curl -s --request GET --header "PRIVATE-TOKEN: ${GITTOKEN}" -F per_page=50 -F page=${page} -F ref=${branch} ${GITAPI}/projects/atlas-tdaq-software%2F${project}/repository/tree > ${tc}/tree
    python - > ${tc}/modules <<EOF
from __future__ import print_function

import sys
import json

repo = json.load(open("${tc}/tree"))
if len(repo) == 0:
    sys.exit(1)
for r in repo:
    if r['mode'] == '160000' and r['type'] == 'commit':
        print(r['name'],r['id'],sep='\t')
EOF

    [ $? -ne 0 ] && break

    grep "${pattern}" ${tc}/modules | while read pkg ref
    do
        pkgrepo=$(git config -f ${tc}/.gitmodules --get submodule.${pkg}.url)
        case ${pkgrepo} in
            ../*)
                pkgrepo=${GITROOT}$(echo $pkgrepo | sed 's;^\.\.;;')
                ;;
            *)
                ;;
        esac

        ref=$(echo $ref | tr -d '-')

        tag=$(git ls-remote --tags ${pkgrepo} | grep "^${ref}"| head -1 | cut -d' ' -f2 | sed -e 's;^.*refs/tags/;;' -e 's;\^{};;')
        printf "%-20s %-20s\n" ${pkg} ${tag:=${ref}}
    done

    page=$(expr ${page} + 1)

done
