#!/bin/bash
if [ -z "$1" ] ; then
  echo "error: missing target"
  exit 1
fi
case "$1" in
  epel-6-*|epel-7-*)
    CMAKE=cmake3
    ;;
  *)
    CMAKE=cmake
    ;;
esac
if [ -n "$2" ] ; then
  DEVTOOLSET_SCL_PREFIX="$2-"
  DEVTOOLSET_SCL_ENABLE="scl enable $2 "
else
  DEVTOOLSET_SCL_PREFIX=
  DEVTOOLSET_SCL_ENABLE=
fi

GITHASH=`git rev-parse master`
NVERSION=2.10.0
LVERSION=5.5.2.11

BUILDSCRIPTSDIR=`pwd`
DIRNAME=bbowda-$GITHASH
FILENAME=$DIRNAME.tar.gz
if [ ! -f "$FILENAME" ] ; then
  echo "--- generating $FILENAME ---"
  cd ..
  git archive -o "$BUILDSCRIPTSDIR/$FILENAME" --prefix="$DIRNAME/" "$GITHASH" || exit $?
  cd "$BUILDSCRIPTSDIR"
fi

NDIRNAME=nlopt-$NVERSION
NFILENAME=$NDIRNAME.tar.gz
if [ ! -f "$NFILENAME" ] ; then
  echo "downloading $NFILENAME"
  wget https://github.com/stevengj/nlopt/archive/v$NVERSION/$NFILENAME || exit $?
fi

LFILENAME=lp_solve_${LVERSION}_source.tar.gz
if [ ! -f "$LFILENAME" ] ; then
  echo "downloading $LFILENAME"
  wget "https://downloads.sourceforge.net/project/lpsolve/lpsolve/$LVERSION/$LFILENAME" || exit $?
fi

echo "--- initializing $1 chroot ---"
mock -r "$1" --init || exit $?
echo "--- installing $CMAKE ---"
mock -r "$1" --install "$CMAKE" || exit $?
echo "--- installing ${DEVTOOLSET_SCL_PREFIX}gcc-c++ ---"
mock -r "$1" --install "$DEVTOOLSET_SCL_PREFIX"gcc-c++ || exit $?
case "$1" in
  epel-7-x86_64)
    echo '--- installing swig4 ---'
    mock -r "$1" --addrepo "https://repo.cloudlinux.com/other/cl7/ext4php/x86_64/" --install swig4 || exit $?
    ;;
  *)
    echo '--- installing swig ---'
    mock -r "$1" --install swig || exit $?
    ;;
esac
echo '--- installing java-1.6.0-openjdk-devel --- '
mock -r "$1" --install java-1.6.0-openjdk-devel || exit $?
echo '--- mkdir -p /builddir/bbowda ---'
mock -r "$1" --unpriv --chroot 'mkdir -p /builddir/bbowda' || exit $?
echo '--- copying sources in ---'
mock -r "$1" --copyin build.sh "$FILENAME" "$LFILENAME" "$NFILENAME" *.patch /builddir/bbowda/ || exit $?
echo '--- chown -R --reference=/builddir/bbowda /builddir/bbowda/* ---'
mock -r "$1" --chroot 'chown -R --reference=/builddir/bbowda /builddir/bbowda/*' || exit $?
echo "--- sed -i -e 's/^cmake /$CMAKE /g;s/^GITHASH=.*"\$"/GITHASH=$GITHASH/g' build.sh"
mock -r "$1" --unpriv --cwd=/builddir/bbowda --chroot "sed -i -e 's/^cmake /$CMAKE /g;s/^GITHASH=.*"\$"/GITHASH=$GITHASH/g' build.sh" || exit $?
echo "--- $DEVTOOLSET_SCL_ENABLE./build.sh ---"
mock -r "$1" --unpriv --enable-network --cwd=/builddir/bbowda --chroot "$DEVTOOLSET_SCL_ENABLE"'./build.sh' || exit $?
echo '--- copying results out ---'
case "$1" in
  *x86_64*)
    BITS=64
    ;;
  *)
    BITS=32
    ;;
esac
for i in libbbowdajnix$BITS.so bbowda.jar ; do
  mock -r "$1" --copyout /builddir/bbowda/$i $i || exit $?
done
echo '--- cleaning chroot ---'
mock -r "$1" --clean || exit $?
exit 0
