#!/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
CWD="$(dirname "$0")"
COMPONENT="hue"

# Adding local PyPi URL
f=~/.pydistutils.cfg
url='https://pypi.infra.cloudera.com/api/pypi/pypi-public/simple/'
echo "[easy_install]" >> "$f"
echo "index_url=$url" >> "$f"
export PYPI_MIRROR="$url"


# This file can be called in two ways. In the normal path, it is
# invoked here as-is, and the build functions are over in the
# templates directory.  As part of packaging, it is copied into a
# package-specific directory along with the contents of the templates
# directory, and so the build functions are in the currrent working
# directory.
FUNCTIONS1="${CWD}/../../templates/buildfuncs"
FUNCTIONS2="${CWD}/buildfuncs"
if [ -f "${FUNCTIONS1}" ]; then
    . "${FUNCTIONS1}"
elif [ -f "${FUNCTIONS2}" ]; then
    . "${FUNCTIONS2}"
else
    echo "Unable to source ${FUNCTIONS1} or ${FUNCTIONS2}"
    exit 1
fi

# Setup Python 2.7 Path required for Hue in C6
# file tools/enable-python27.sh is located in Hue code
source tools/enable-python27.sh

mvn $CAULDRON_MAVEN_EXTRA_ARGS -f maven/pom.xml install "$@"

if [[ -n "${CAULDRON_PKG_BUILD_MVN_PHASE}" ]]; then
  # We are in the maven-only phase of Cauldron build. Don't run any
  # OS-specific stuff below
  echo "Maven-only phase of Cauldron build. Nothing more to do - exiting."
  exit 0
fi

MAVEN_OPTIONS=$DO_MAVEN_DEPLOY make apps docs

# Copy generated docs
if [ -n "$CAULDRON_FIRST_NATIVE_BUILD" ]; then
  # We only need to copy docs once regardless of OS
  PUB_DOCS_DIR="${CAULDRON_OUTPUT}/cdh6/${CDH_VERSION}/docs/${COMPONENT}-${FULL_VERSION}/"
  mkdir -p "${PUB_DOCS_DIR}"
  cp -r build/docs/* "${PUB_DOCS_DIR}"
fi

# Make the entire tree relocatable
bash tools/relocatable.sh

# Cloudera specific
if [ -f Makefile.tarball ] ; then
    make prod
    rm -rf build/release/prod/"${COMPONENT}"-*.tgz "build/release/prod/${COMPONENT}-${FULL_VERSION}"
    mv build/release/prod/"${COMPONENT}"-* build/release/prod/"${COMPONENT}-${FULL_VERSION}"
    cp -r cloudera "build/release/prod/${COMPONENT}-${FULL_VERSION}"
    tar --use-compress-program pigz -C build/release/prod -cf "build/${COMPONENT}-${FULL_VERSION}.tar.gz" "${COMPONENT}-${FULL_VERSION}"
fi
