#!/usr/bin/env bash

MODULES=(api client server .)
tmp="target/tmp.txt"
tickets="target/tickets.txt"

for MODULE in "${MODULES[@]}" ; do
  cd ${MODULE}
  #CURRENT_MODULE_ARTIFACT=`xpath -q -e '/project/artifactId/text()' pom.xml` # works on Linux
  CURRENT_MODULE_ARTIFACT=`xpath pom.xml '/project/artifactId/text()'` # works on macOS

  mkdir -p target ;
  current_branch=$( git branch | grep \* | cut -d ' ' -f2 );

  if [[ ${current_branch} != "master" ]] ; then
    BRANCH_SUFFIX="-`basename $current_branch`"
  else
    BRANCH_SUFFIX="";
  fi

  tags_string=$( git tag | grep -o -e "$CURRENT_MODULE_ARTIFACT-[0-9]\+\(\.[0-9]\+\)*$BRANCH_SUFFIX$" | sort -r );
  IFS=' ' read -r -a tag <<< "$tags_string";

  if [[ -f release.marker ]] ; then
    ( git log ${tag}..${current_branch} | grep -o -e "DISPENSER-[0-9]\+" | sort | uniq >> ${tmp})
  fi

  echo " **** Git log: **** " > target/gitlog-from-tag.txt;
  echo >> target/gitlog-from-tag.txt;
  ( git log ${tag}..${current_branch} >> target/gitlog-from-tag.txt )
  echo >> target/gitlog-from-tag.txt;

  echo " **** Affected files: **** " >> target/gitlog-from-tag.txt;
  echo >> target/gitlog-from-tag.txt;
  ( git diff --name-status ${tag}..${current_branch} -- . >> target/gitlog-from-tag.txt );
  cd -
done

cat ${tmp} | sort | uniq > ${tickets}
rm -rf ${tmp}
