#!/bin/bash

set -xe

arg_buld_name="${1:?Missing build name argument.}"
arg_cpu_count="$(nproc)"

if [[ -z "${arg_cpu_count}" ]]; then
  echo "could not get cpu count"
  exit 1
fi

# Clear build results if source is missing.
if ! [[ -d /build/source ]]; then
  rm -rf /build /prefix || :
  cp -rp /deploy/build /
  cp -rp /deploy/prefix /
  cd /build
fi

rsync-update /data/${arg_buld_name}/ /build/source/

cd /build/source

if ! [[ -f "./configure" ]]; then
  echo -e "\033[0;32m${arg_buld_name} autogen.sh\033[0m"
  ./autogen.sh
fi

cd /build/output

if ! [[ -f "./config.h" ]]; then
  echo -e "\033[0;32m${arg_buld_name} configure\033[0m"
  . /env.configure
  /build/source/configure --prefix=/prefix --disable-backtrace
fi

make_args=(-j $(( ${arg_cpu_count} * 2 )) )

make "${make_args[@]}"
make "${make_args[@]}" install
make "${make_args[@]}" install install
make "${make_args[@]}" check TESTS=
make "${make_args[@]}" check
