
#!/bin/bash

set -euo pipefail

NO_CHK=${2-}

if [[ -z ${NO_CHK} ]] && [[ ! -e o2_nrConfs.txt ]]; then
  echo "o2_nrConfs.txt not found, exiting"
  exit 1
fi
I=${1-}
if [[ ! $I =~ ^(0|[1-9][0-9]*)$ ]]; then
  echo "ID of the configuration to build required (natural number)"
  exit 2
fi
if [[ -z ${NO_CHK} ]] && ([[ $I -lt 0 ]] || [[ $I -gt $(cat o2_nrConfs.txt) ]]); then
  echo "given ID out of range, must be in range [0;$(cat o2_nrConfs.txt)]"
  exit 3
fi

TMP_DIR=$(mktemp -d --tmpdir=/dev/shm || mktemp -d --tmpdir=/tmp || echo "")
function cleanup {
  if [[ -n "${TMP_DIR}" ]]; then
    rm -rf "${TMP_DIR}"
  fi
}
trap cleanup EXIT

LOG=scratch/o4/compile-$I.log
exec &> >(tee ${LOG})

DIR=scratch/$(printf "var%05d" $I)

if [[ -n "${TMP_DIR}" ]]; then
  cp -r ${DIR}/* ${TMP_DIR}
  make -j2 -C ${TMP_DIR}
  mv ${TMP_DIR}/exastencils ${DIR}/exastencils.exe
else
  make -j2 -C ${DIR}
  mv ${DIR}/exastencils ${DIR}/exastencils.exe
  make -C ${DIR} clean
fi
