#!/bin/bash

# Search for python
python=$(which python python2 python3 | tail -1)

# Define the target build directory
prefix=$(pwd)/build

bypass=
clean=

srcdir=.
while [ $# -gt 0 ]
do
   case "${1}" in
      --srcdir=*)
         srcdir=${1#*=}
      ;;

      --build)
         bypass=":"
      ;;

      --clean)
         clean="yes"
      ;;
   esac
   shift
done

function waf
{
   pkg="$1"
   shift

   mkdir -p ${pkg}
   pushd >/dev/null ${pkg}

   if [ ! -e "waf" ]
   then
      cp -pr "../${srcdir}/${pkg}"/{waf,waflib} .
   fi
   
   for f in "../${srcdir}/${pkg}"/*
   do
      [ ! -e "${f##*/}" ] && ln -s "${f}"
   done

   export CFLAGS="${CFLAGS/++14/11}" # Circumvent travis setting
   export PKG_CONFIG_PATH="${prefix}/lib/pkgconfig"
   export LDFLAGS="${LDFLAGS} -ldl -lm"

   common="--prefix=${prefix} --out=build --destdir=/"

   if [ "${clean}" = "yes" ]
   then
      ${python} waf clean ${common} || exit 1
   else
      ${bypass} ${python} waf configure ${common} $@ || exit 1

      trap "rm -f .build-timestamp" EXIT
      touch .build-timestamp

      ${python} waf build ${common} $@ || exit 1
      if [ -n "$(find . -newer .build-timestamp -type f ! -name compile_commands.json)" ]
      then
         ${python} waf install ${common} $@ || exit 1
      fi

      rm .build-timestamp
      trap - EXIT
   fi

   popd >/dev/null
}

[ ! -e Makefile ] && ln -s "${srcdir}/Makefile"
[ ! -e configure ] && ln -s "${srcdir}/configure"

waf lv2    --no-plugins --no-coverage
waf serd   --static --no-shared --no-coverage --no-utils --largefile
waf sord   --static --no-shared --no-coverage --no-utils
waf sratom --static --no-shared --no-coverage
waf lilv   --static --no-shared --no-coverage --no-utils
waf suil   --static --no-shared

exit 0
