#!/bin/bash

piece=$1
ooo_build_tag=$2

source $OO_TOOLSDIR/piece/sys-setup

custom_env="$OO_TOOLSDIR/piece/env-$piece"
if test -f $custom_env; then
   source $custom_env
   echo "merged custom environment: $custom_env"
fi

custom_unpack="$OO_TOOLSDIR/piece/unpack-$piece"
export GNUCP=cp
if test -f $custom_unpack; then
    echo "Invoke custom unpack: $custom_unpack"
    $custom_unpack $OO_TOOLSDIR/.. `pwd`
fi

$OO_TOOLSDIR/install-artwork $OO_TOOLSDIR/../src `pwd`

# new modules
test "$piece" = "libs-core" && mkdir -p vbahelper
test "$piece" = "filters" && mkdir -p lotuswordpro

# apply flags
builddir=`pwd`
FLAGS=`$OO_TOOLSDIR/applyflags $OO_TOOLSDIR $builddir`
# explicitely add --distro=System
# it can't be detected easily
FLAGS="$FLAGS --additional-sections=System"
# additional piece-specific sections added in the package sources (special build)
additional_sections_file="$builddir/ooo-build/apply-additional-sections"
if test -f "$additional_sections_file" ; then
    for section in `sed "s|,| |g" $additional_sections_file` ; do
	FLAGS="$FLAGS --additional-sections=$section"
    done
fi
# additional piece specifix hotfixes added in the package sources (special build)
FLAGS="$FLAGS --hotfixes=$builddir/ooo-build/hotfixes"

# finally call apply.pl
$OO_TOOLSDIR/../patches/apply.pl $OO_TOOLSDIR/../patches/dev300 \
    --tag=$ooo_build_tag $FLAGS $builddir || exit 1;

# available source dirs
# FIXME: omit optional directories that are not enabled (--with-system-XXX, ...)
omit_dirs="-e applied_patches -e ^solver -e ooo-build -e javainstaller2"
if test "$piece" != "libs-extern" -a "$piece" != "libs_extern" ; then
    omit_dirs="$omit_dirs -e ^external\$"
fi
dirs=`/bin/ls | grep -v $omit_dirs | tr '\n' ':'`
# clean build?
if test ! -d solver; then
    echo "A very clean straight-through build - deferring dep generation"
    export nodep=1
fi

# apply extra localization fixes in the libs-gui piece
if test "$piece" = "libs-gui" -o "$piece" = "libs_gui" ; then
    # do not build modules depending on transex3,l10n,vcl now
    for dir in * ; do 
	test -f $dir/prj/build.lst && \
	head -n 1 $dir/prj/build.lst | grep -q -e transex3 -e l10n -e vcl && \
	omit_dirs="$omit_dirs -e ^$dir\$"
	transex3_dirs=`/bin/ls | grep -v $omit_dirs | tr '\n' ':'`
	# actually build the transex3 module
	transex3_dirs="transex3:$transex3_dirs"
    done
    # build the localize tool
    perl $SOLARENV/bin/build.pl --subdirs:$transex3_dirs $EXTRA_BUILD_FLAGS $EXTRA_DMAKE_FLAGS || exit 1;
    unset nodep
    # apply sdf files
    $OO_TOOLSDIR/localize-ooo || exit 1;
fi

# final build
perl $SOLARENV/bin/build.pl --subdirs:$dirs $EXTRA_BUILD_FLAGS $EXTRA_DMAKE_FLAGS || exit 1;
