#!/usr/bin/env bash

set -e

START_TAG="swarm_repository_listing_begin"
END_TAG="swarm_repository_listing_end"

strict=true
prod=false
mavenSettings=

while [[ $# -gt 0 ]]
do
case $1 in
    --non-strict)
    echo "strict checking disabled"
    strict=false
    ;;
    --maven-settings)
    mavenSettings="$2"
    echo "maven settings from $mavenSettings will be used"
    shift
    ;;
    --prod)
    prod=true
    ;;
esac
shift # past argument or value
done

function analyzeM2Repo () {
    pushd target

    cd contents/m2repo

    allJars=( $(find . -type f -name '*.jar' | sort) )

    echo "m2repo contents:"
    echo $START_TAG
    printf '%s\n' "${allJars[@]}"
    echo $END_TAG

    echo "duplicate versions:"
    echo $START_TAG
    for jar in ${allJars[@]}
    do
        gaDir="${jar%/*/*}"
        versionCount=$(find $gaDir  -type d -links 2 | wc -l)
        if [[ $versionCount -gt 1 ]]
        then
            find $gaDir -type d -links 2
        fi
    done
    echo $END_TAG

    popd
}

function filterOutExternalArtifacts() {
    if $prod
    then
        verifyM2Repo
        echo "will gather the contents of `pwd`/repository to ${zipContentsDir}"

        modCount=1
        while [[ $modCount -gt 0 ]]
        do
            modCount=$(find repository -type d -links 2 ! -name '*redhat*' -and ! -path '*eap-runtime-artifacts*' -prune -exec rm -rvf {} \; | wc -l)
        done
        echo DONE
    fi
}

function verifyM2Repo () {
    echo "verifying m2 repository"
    pushd target

    cd contents/m2repo

    set +e
    nonRedhat=( $(find . -type f | sort | grep -v "redhat" | grep -v "eap-runtime-artifacts" ) )
    set -e

    echo "3rd party runtime dependencies not matching the pattern"
    echo $START_TAG
    if [[ ${nonRedhat[@]} ]]
    then
        for i in ${nonRedhat[@]}
        do
            echo $i
        done
        echo $END_TAG

        if $strict
        then
            echo "using strict mode, exiting"
            exit 1
        else
            echo "strict mode disabled, continuing"
        fi
    else
        echo $END_TAG
    fi
    popd
}

function generateMissingChecksums (){
    for i in $( find repository -type f | grep -v '.sha1$' | grep -v '.md5$' )
    do
        if [ ! -f "$i.sha1" ]
        then
            sha1sum $i | cut -d ' ' -f 1  | tr -d $'\n'  > $i.sha1
        fi
        if [ ! -f "$i.md5" ]
        then
            md5sum $i | cut -d ' ' -f 1  | tr -d $'\n'  > $i.md5
        fi
    done
}

zipContentsDir="$(pwd)/repository"

cd full-project

analyzeM2Repo
filterOutExternalArtifacts

find repository -type f -name '_remote.repositories' -prune -exec rm -f {} \;
find repository -type f -name '*.lastUpdated' -prune -exec rm -f {} \;

generateMissingChecksums

mv repository ${zipContentsDir}
