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

# drop --distro=Localize for now ...
$OO_TOOLSDIR/../patches/apply.pl $OO_TOOLSDIR/../patches/dev300 --pieces \
	--tag=$ooo_build_tag --hotfixes=`pwd`/ooo-build/hotfixes \
	--distro=$DISTRO --distro=Piece --distro=Binfilter \
	--distro=System --distro=Sdk --distro=Extensions \
	 `pwd` || exit 1;

# available source dirs
omit_dirs="-e applied_patches -e ^solver -e ooo-build"
if test "$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

# might need to build localize tool first
if test "$piece" = "libs_gui" ; then
    perl $SOLARENV/bin/build.pl --subdirs:$dirs $EXTRA_BUILD_FLAGS $EXTRA_DMAKE_FLAGS || exit 1;
    unset nodep
fi

# localize
if which localize >/dev/null 2>&1 ; then
    $OO_TOOLSDIR/localize-ooo || exit 1;
fi

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