#!/bin/bash
#
# Show the difference in packages between branches or commits
#
# diff_releases --names-only <project> <commit1> [ <commit2> ]
#

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

usage()
{
    echo "usage: diff_releases [--names-only] <project> <commit> [ <commit> ]"
    echo "   Show the difference in package tags between the two commits"
    echo "   The second commit is HEAD by default"
    echo "   The --names-only option prints only the list of packages without tags"
}

names=0
if [ "$1" == "--names-only" ]; then
    names=1
    shift
fi

[ $# -lt 2 ] && { usage; exit 1; }

project=$1
shift

commit1="$1"
shift

commit2=HEAD
[ $# -gt 0 ] && commit2="$1"

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

git clone -q ${GITROOT}/${project}-cmake.git ${tc} || { echo "Cannot clone ${project}"; exit 2; }

[ -n "$(cd $tc; git branch -r --list origin/${commit1})" ] && commit1=origin/${commit1}
[ -n "$(cd $tc; git branch -r --list origin/${commit2})" ] && commit2=origin/${commit2}

(cd $tc && git diff --submodule "${commit1}" "${commit2}" | grep '^Submodule '| sed -e 's;^Submodule ;;' -e 's;\.\.\.; ;' | cut -d' ' -f1-3 > ${tc}/diff)
if [ $names -eq 1 ]; then
     cut -d' ' -f1 ${tc}/diff | tr '\n' ' '
     exit 0
fi

# arguments: pkg ref module
find_tag()
{
    if [ "$2" == "0000000" ]; then
        tag="-------------------"
    else
        pkgrepo=$(git config -f $3 --get submodule.$1.url)
        case ${pkgrepo} in
            ../../*)
                pkgrepo=$(dirname $GITROOT)$(echo $pkgrepo | sed 's;\.\./\.\.;;')
                ;;
            ../*)
                pkgrepo=${GITROOT}$(echo $pkgrepo | sed 's;^\.\.;;')
                ;;
            *)
                ;;
        esac
        tag=$(cd ${tc}; git ls-remote --tags ${pkgrepo} | grep "^$2" | head -1 | cut -d' ' -f2 | sed -e 's;^.*refs/tags/;;' -e 's;\^{};;')
        if [ -z "${tag}" ]; then tag=$2; fi
    fi
    printf "%-20s %-20s\n" $1 ${tag}
}

(cd ${tc} && git show ${commit1}:.gitmodules > modules1)
(cd ${tc} && git show ${commit2}:.gitmodules > modules2)
cat ${tc}/diff | while read pkg ref1 ref2
do
    find_tag ${pkg} ${ref1} ${tc}/modules1 >> ${tc}/rel1
    find_tag ${pkg} ${ref2} ${tc}/modules2 >> ${tc}/rel2
done

join ${tc}/rel1 ${tc}/rel2 | column -t
