#!/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")"

# 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

# -f src/build.xml
IVY_MIRROR_PROP=${IVY_MIRROR_PROP:-http://repo1.maven.org/maven2/}

mkdir -p build

if [ -z "${DO_MAVEN_DEPLOY}" ]; then
    MAVEN_INST_DEPLOY=install
else
    MAVEN_INST_DEPLOY=$DO_MAVEN_DEPLOY
fi

if [ -z "${MAVEN_DEPLOY_ONLY}" ]; then
    MAVEN_ARGS="-Psources -Pjavadoc"
else
    MAVEN_ARGS="-Denforcer.skip=true"
fi

mvn $CAULDRON_MAVEN_EXTRA_ARGS $MAVEN_INST_DEPLOY -DskipTests ${MAVEN_ARGS} -Phadoop-2 -fae "$@"

if [ -z "${MAVEN_DEPLOY_ONLY}" ]; then
    (cd packaging; mvn package -Pdist)
    mkdir -p build/hive-${FULL_VERSION}
    tar --use-compress-program pigz --strip-components 1 -C build/hive-${FULL_VERSION} -xf packaging/target/apache-hive*bin.tar.gz
    mkdir -p build/hive-${FULL_VERSION}/docs
    mkdir -p build/hive-${FULL_VERSION}/data/scripts
    cp -r docs/* build/hive-${FULL_VERSION}/docs
    cp data/scripts/q_test_*.sql build/hive-${FULL_VERSION}/data/scripts
    (cd build && tar --use-compress-program pigz --exclude='*/native/lib*' --exclude='*/lib/native/*' -cf hive-${FULL_VERSION}.tar.gz hive-${FULL_VERSION})
fi
