#!/bin/bash

while test $# -gt 0; do
    case "$1" in
            -h|--help)
                    echo "This creates JDG depdency information for building Brew repository"
                    echo " "
                    echo "if no arguments specified - assume infinispan project to build and current directory is packaging"
                    echo " "
                    echo "options:"
                    echo "-h, --help                Show brief help"
                    echo "--projects                List of projects to be built"
                    exit 1
                    ;;
            --projects*)
                    PROJECTS=`echo $2`
                    shift
                    ;;
            *)
                    shift
                    ;;
    esac
done

# Solves sorting issues
LANG=C
DIR=`dirname $0`
BASEDIR=`readlink -f "$DIR"`
OUTPUT=`pwd`/target/dependency-report

rm -rf $OUTPUT
mkdir -p $OUTPUT

if [ -z $PROJECTS ]; then
    PROJECTS="infinispan"
fi

IT_REGEX="^integrationtests.*"

for PROJECT in $PROJECTS; do
    echo "Processing $PROJECT"
    pushd ../$PROJECT > /dev/null
    MODULES=`xsltproc $BASEDIR/module-list.xslt pom.xml`
    xsltproc $BASEDIR/extract-gav.xslt pom.xml > $OUTPUT/module-$PROJECT.txt
    for MODULE in $MODULES; do
                if [[ $MODULE =~ $IT_REGEX ]]; then
                    continue
                fi
        echo "  Processing $MODULE"
        DEPS=`echo $MODULE|tr / -`
        xsltproc $BASEDIR/extract-gav.xslt $MODULE/pom.xml > $OUTPUT/module-$PROJECT-$DEPS.txt
        mvn -s "$BASEDIR/maven-settings.xml" org.apache.maven.plugins:maven-dependency-plugin:2.8:list -DincludeParents=true -pl $MODULE | cut -c 11- | egrep ":(compile|pom)" | grep -v "^Some problems" | sort >> $OUTPUT/module-$PROJECT-$DEPS.txt
    done
    popd > /dev/null
done

cat $OUTPUT/module-* | sort | uniq > $OUTPUT/global.txt
cat $OUTPUT/global.txt | cut -d: -f 1,2,4 | sort > $OUTPUT/all-artifacts.txt

while read IN; do
    GAV=(${IN//:/ })
    echo -n ${GAV[0]} |tr . / >> $OUTPUT/all-artifact-paths.txt
    echo /${GAV[1]}/${GAV[2]} >> $OUTPUT/all-artifact-paths.txt
done < $OUTPUT/all-artifacts.txt
cat src/main/resources/artifacts/*.txt | sort | uniq > $OUTPUT/eap-artifacts.txt
cat $OUTPUT/all-artifact-paths.txt | sort | uniq > $OUTPUT/jdg-artifact-paths.txt

comm -1 -3 $OUTPUT/eap-artifacts.txt $OUTPUT/jdg-artifact-paths.txt | grep -E '[0-9]+.[0-9]+-[0-9]+|redhat[-.]' > $OUTPUT/jdg-artifacts.txt

