#!/bin/bash
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -ex

GRADLE_ARGS="--console=plain --no-daemon"

if [ -n "${MAVEN_DEPLOY_ONLY}" ]; then
    pushd java
    # Ensure we start with a clean environment
    ./gradlew $GRADLE_ARGS clean --refresh-dependencies
    # We're in the maven phase of the package build. Deploy the maven artifacts.
    if [ -z "$DO_MAVEN_DEPLOY" ]; then
        # TODO: unreachable code; if MAVEN_DEPLOY_ONLY is set,
        # DO_MAVEN_DEPLOY must be set too?
        ./gradlew $GRADLE_ARGS install -PskipSigning=true
    else
        ./gradlew $GRADLE_ARGS uploadArchives -PskipSigning=true
    fi
    popd
    exit 0
fi

if  [ -z "$CAULDRON_PKG_BUILD_MVN_PHASE" -a -n "$CAULDRON_ROOT_DIR" ]; then
    # We're in the packaging phase. Reuse the artifacts generated in the
    # maven phase.
    #
    # Yes, this copies the entire source tree, but -n ensures that only new
    # files will be copied, which should just be the java build output
    # generated earlier.
    echo "Copying artifacts generated in the maven build phase..."
    cp -n -R ${CAULDRON_ROOT_DIR}/build/docker.common/build/cdh/kudu/*/source/* .
fi

# Enable ccache and log a log file.
export PATH=/usr/local/lib/ccache/:$PATH  # Enable ccache
export CCACHE_LOGFILE=${CAULDRON_OUTPUT}/logs/ccache-log-kudu-$$.txt
ccache -s || true   # Dump statistics, never fail.

# Tune Make's parallelism to take into account that, in the Cauldron
# context, multiple copies of the Kudu build will be running in parallel,
# and, if all of them run a lot of C++ processes, the build machine will
# run out of memory.  We use both --load-avg and -j to effect this.
# Surprisingly, --load-avg is not sensitive enough when five builds are
# going on at the same time.
#
# (Adapted from impala/do-component-build)
target_load=$(nproc)
KUDU_BUILD_THREADS=$(( $(nproc) / ${CAULDRON_NUM_OS:-1} ))
if [[ ${KUDU_BUILD_THREADS} -lt 1 ]]; then
  KUDU_BUILD_THREADS=1
fi
KUDU_MAKE_FLAGS="--load-average=${target_load}"

# Build thirdparty.
ENABLE_DEVTOOLSET="$(pwd)/build-support/enable_devtoolset.sh"
export PARALLEL="${KUDU_BUILD_THREADS}"
export EXTRA_MAKEFLAGS="${KUDU_MAKE_FLAGS}"
export DEPENDENCY_URL=http://cloudera-thirdparty-libs.s3.amazonaws.com
${ENABLE_DEVTOOLSET} ./thirdparty/build-if-necessary.sh

# Force cmake to omit the call to build-if-necessary.sh.
export NO_REBUILD_THIRDPARTY=1

CMAKE="$(pwd)/thirdparty/installed/common/bin/cmake"

# Always static link.
CMAKE="${CMAKE} -DKUDU_LINK=static"

# Skip building of unit tests to save time.
CMAKE="${CMAKE} -DNO_TESTS=1"

# Provide the git hash collected earlier.
CMAKE="${CMAKE} -DKUDU_GIT_HASH=$(cat kudu_git_hash)"

MAKE="make -j${KUDU_BUILD_THREADS} ${KUDU_MAKE_FLAGS}"
for type in release fastdebug; do
  mkdir -p build/${type}
  pushd build/${type}
  rm -rf CMakeCache.txt CMakeFiles/
  ${ENABLE_DEVTOOLSET} ${CMAKE} -DCMAKE_BUILD_TYPE=${type} ../..
  ${MAKE}
  ${MAKE} install DESTDIR=$(pwd)/client
  popd
done

# Ensure the base Kudu version we're building is the one we're expecting.
CDH_VERSION=$(awk -F= '$1 == "version" { print $2 }' cloudera/build.properties | cut -d- -f 1 | head -n 1)
KUDU_VERSION=$(cat version.txt | cut -d- -f 1 | head -n 1)
[[ "${CDH_VERSION}" == "${KUDU_VERSION}" ]]

ccache -s || true   # Dump statistics, never fail.

# Kudu binaries are needed in order to build the Kudu CSDs. The semantics of
# CAULDRON_FIRST_NATIVE_BUILD guarantee that this will only happen once.
if [ -n "$CAULDRON_FIRST_NATIVE_BUILD" ]; then
    pushd java

    # First, build the CSDs.
    CSD_TASKS=$(find kudu-csd* -type d -maxdepth 0 -exec echo {}:assemble \; | tr '\n' ' ')
    echo "Running the following CSD tasks: $CSD_TASKS"
    ./gradlew -PbuildCSD $GRADLE_ARGS $CSD_TASKS

    # Next, install them into Cauldron's CSD repo.
    for JAR in kudu-csd*/build/libs/*.jar; do
        if [[ "$JAR" =~ "tests" ]]; then
            # Ignore test JARs.
            continue
        fi

        # Need to override packaging from 'pom' to 'jar' because Maven!
        mvn org.apache.maven.plugins:maven-install-plugin:2.5.2:install-file \
            -Dfile="$JAR" \
            -DlocalRepositoryPath="$CSD_REPO_BASE_PATH" \
            -Dpackaging=jar \
            -DpomFile="$(dirname $JAR)/../pom.xml"
    done
    popd
fi
