#!/usr/bin/env bash

set -e

# Set proxy
#export http_proxy=http://${buildContentId}+tracking:${accessToken}@${proxyServer}:${proxyPort}

# Copy files for main build
cp -rv redhat/* ./

# Detect my own version (which changes during productization)
echo "Detecting project version"
mvn org.apache.maven.plugins:maven-help-plugin:3.1.1:evaluate -Dexpression=project.version
export MY_VERSION=$(mvn org.apache.maven.plugins:maven-help-plugin:3.1.1:evaluate -Dexpression=project.version -q -DforceStdout)
echo "Building version ${MY_VERSION}"
echo ""

# Support tasks
pushd maven-dependencies

# echo "Set new version $MY_VERSION for the helper Maven project"
# mvn org.codehaus.mojo:versions-maven-plugin:2.7:set -DnewVersion=$MY_VERSION

# generate the CVE check list
# Doesn't work on PNC because of Proxy
# echo "Run CVE check"
# mvn com.redhat.victims.maven:security-versions:check
# tar -z -cf kafka-cve-check-$MY_VERSION.tgz -C target/dependencies/ .  || [[ $? -eq 1 ]]
# mvn deploy:deploy-file -Durl=${AProxDeployUrl} -DrepositoryId=indy-mvn -Dfile=kafka-cve-check-$MY_VERSION.tgz -Dclassifier=dist -Dtype=tgz -DgroupId=org.apache.kafka -DartifactId=kafka-cve-check -Dversion=$MY_VERSION
# mvn clean

# License files
echo "Collect licences"
#mkdir -p target/licenses
# cp -rv src/main/resources/template/*.css target/licenses/
# cp -rv src/main/resources/licenses/* target/licenses/
# mvn org.wildfly.maven.plugins:licenses-plugin:insert-versions -Dlicense.includeOptionalDependencies=false -DincludeTransitiveDependencies=false -Dlicense.includedScopes=runtime,compile -Dlicense.excludedGroups=org.apache.ant package
# cp -rv target/licenses ../
tar -z -cf kafka-licenses-$MY_VERSION.tar.gz -C ../licenses/ .  || [[ $? -eq 1 ]]
mvn deploy:deploy-file -Durl=${AProxDeployUrl} -DrepositoryId=indy-mvn -Dfile=kafka-licenses-$MY_VERSION.tar.gz -Dpackaging=tar.gz -DgroupId=org.apache.kafka -DartifactId=kafka-licenses -Dversion=$MY_VERSION
#mvn clean

popd

# Main Kafka build
echo "Run main build"
mvn -e -V -B deploy

echo "Collect the build project for system tests"
tar -z --exclude='*.tar.gz' --exclude='*.tgz' --exclude='*.zip' -cf kafka-build-project-$MY_VERSION.build-project.tar.gz ./  || [[ $? -eq 1 ]]
mvn deploy:deploy-file -Durl=${AProxDeployUrl} -DrepositoryId=indy-mvn -Dfile=kafka-build-project-$MY_VERSION.build-project.tar.gz -Dpackaging=tar.gz -DgroupId=org.apache.kafka -DartifactId=kafka-build-project -Dversion=$MY_VERSION