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

if [ -z "$GIT_REPO" ]; then
    if [ -z "${DO_MAVEN_DEPLOY}" ]; then
        MAVEN_INST_DEPLOY=install
    else
        MAVEN_INST_DEPLOY=$DO_MAVEN_DEPLOY
    fi
    
    export MAVEN_OPTS="-Xmx2g -XX:ReservedCodeCacheSize=512m -XX:PermSize=1024m -XX:MaxPermSize=1024m"
    mvn $CAULDRON_MAVEN_EXTRA_ARGS -N $MAVEN_INST_DEPLOY

    # This is here to make sure that we ignore any errors due to the circular dependency with Hadoop when
    # we are doing a maven-only build for version updating.
    if [ -n "${MAVEN_ONLY}" ]; then
        NEVER_FAIL=-fn
    fi

    # Build Java libraries
    (cd lang/java;
        mvn $CAULDRON_MAVEN_EXTRA_ARGS package -DskipTests -Dhadoop.version=2 $NEVER_FAIL $@;
        rm -rf mapred/target/classes/;
        mvn $CAULDRON_MAVEN_EXTRA_ARGS -Dhadoop.version=2 -P dist package compile -DskipTests -DskipITs -Davro.version=$VERSION $NEVER_FAIL $MAVEN_INST_DEPLOY $@
        mvn $CAULDRON_MAVEN_EXTRA_ARGS javadoc:aggregate )

    if [ -z "${MAVEN_ONLY}" ]; then
        (cd lang/java/trevni/doc; mvn site $@)
        mvn $CAULDRON_MAVEN_EXTRA_ARGS -N -P copy-artifacts antrun:run $@
        (cd doc; ant -Dforrest.home=${FORREST_HOME};)
        
    # Some Avro docs get placed in folders with special characters in the name
        (cd build;
            mkdir -p avro-doc-placeholder
            mv avro-doc-${FULL_VERSION}*/* avro-doc-placeholder/
            rm -rf avro-doc-${FULL_VERSION}*
            mv avro-doc-placeholder avro-doc-${FULL_VERSION})
        
        ALL_FILES=`ls`
        mkdir -p avro-${FULL_VERSION} build
        cp -r ${ALL_FILES} avro-${FULL_VERSION}/
        tar czf build/avro-${FULL_VERSION}.tar.gz avro-${FULL_VERSION}
    fi
else
    git add .
    git commit -a -m "Temporary commit for tarball"
    mkdir -p build
    git archive --prefix=avro-${FULL_VERSION}/ --format=tar HEAD |gzip > build/avro-${FULL_VERSION}.tar.gz
fi

