#! /usr/bin/env bash

trap 'exit 1' ERR

build=build-0.3.3-1
libcult=libcult-1.4.2
libfe=libfrontend-elements-1.1.1
libbe=libbackend-elements-1.6.1
libxsd_fe=libxsd-frontend-1.15.0
xsd=xsd-3.2.0-2

pwd=`pwd`

MAKEFLAGS="-I$pwd/install/include $MAKEFLAGS"

target=$1

if [ "$target" = "install" ]; then
  # Since we only want to install XSD, we will handle
  # this target at the end.
  target=
fi


# build
#
if [ ! -d $pwd/install/include/build-* ]; then
  make -C $build install_prefix=$pwd/install install
fi


# libcult
#
make $MAKEFLAGS -C $libcult/cult $target

if [ "$target" = "clean" ]; then
  rm -f $pwd/install/include/cult
  rm -f $pwd/install/lib/libcult.a
  rm -f $libcult/build/system/configuration-dynamic.make
else
  if [ ! -d $pwd/install/include/cult ]; then
    ln -s ../../$libcult/cult install/include/
    ln -s ../../$libcult/cult/libcult.a install/lib/
  fi
fi


# libfrontend-elements
#
make $MAKEFLAGS -C $libfe/frontend-elements $target

if [ "$target" = "clean" ]; then
  rm -f $pwd/install/include/frontend-elements
  rm -f $pwd/install/lib/libfrontend-elements.a
else
  if [ ! -d $pwd/install/include/frontend-elements ]; then
    ln -s ../../$libfe/frontend-elements install/include/
    ln -s ../../$libfe/frontend-elements/libfrontend-elements.a install/lib/
  fi
fi


# libbackend-elements
#
make $MAKEFLAGS -C $libbe/backend-elements $target

if [ "$target" = "clean" ]; then
  rm -f $pwd/install/include/backend-elements
else
  if [ ! -d $pwd/install/include/backend-elements ]; then
    ln -s ../../$libbe/backend-elements install/include/
  fi
fi


# libxsd-frontend
#
make $MAKEFLAGS -C $libxsd_fe/xsd-frontend $target

if [ "$target" = "clean" ]; then
  rm -f $pwd/install/include/xsd-frontend
  rm -f $pwd/install/lib/libxsd-frontend.a
else
  if [ ! -d $pwd/install/include/xsd-frontend ]; then
    ln -s ../../$libxsd_fe/xsd-frontend install/include/
    ln -s ../../$libxsd_fe/xsd-frontend/libxsd-frontend.a install/lib/
  fi
fi


# xsd
#
if [ "$target" = "clean" ]; then
  make $MAKEFLAGS -C $xsd clean
else
  make $MAKEFLAGS -C $xsd/xsd $target
fi

if [ "$target" = "clean" ]; then
  rm -f $pwd/install/include/xsd
  rm -f $pwd/install/bin/xsd
else
  if [ ! -d $pwd/install/include/xsd ]; then
    ln -s ../../$xsd/libxsd/xsd install/include/
    ln -s ../../$xsd/xsd/xsd install/bin/
  fi
fi

if [ "$1" = "install" ]; then
make $MAKEFLAGS -C $xsd install
fi

# build (clean)
#
if [ "$target" = "clean" ]; then
  rm -rf $pwd/install/include/build-*
fi
