#!/usr/bin/env bash

set -e

unset LD_{RUN,LIBRARY}_PATH LIBRARY_PATH CPATH {C,CPLUS}_INCLUDE_PATH PYTHONPATH
unset "${!EUPS_@}" "${!LSST_@}" SETUP_EUPS

source "$(dirname "$0")/lib/install.rc"

source "$(dirname "$0")/libversions"
source "$(dirname "$0")/variables"

if [[ $nproc -ge 2 ]]
then
  export MAKEFLAGS="-j $(($nproc))"
  export EUPSPKG_SCONSFLAGS="-j $(($nproc))"
fi

workdir="${workdir:-/tmp}"/hscpipe_build_dir

lsst_home="${prefix}/lsst_home"


main()
(
  export PATH="$path"
  install_gcc
  export PATH="$prefix/bin:$PATH"

  install_binutils
  install_git
  install_sqlite3
  install_python

  install_openblas
  install_numpy

  # In addition to numpy, we need to pre-install several python libraries.
  # To know what to pre-install:
  #     'find {stack_dir}/Linux64 -name check_python_module'
  pip3 install scipy
  pip3 install matplotlib
  pip3 install astropy

  export EUPS_PKGROOT_BASE_URL="${eups_pkgroot_base_url}"

  mkdir -p "${lsst_home}"
  pushd "${lsst_home}"

  install_eups

  # We replace the build directory (EupsBuildDir)
  # with a symbolic link to a subdirectory of $workdir
  if :
  then
    miniconda_dir=(stack/miniconda*)
    rm -rf "$miniconda_dir/EupsBuildDir"
    mkdir -p "$workdir/EupsBuildDir/Linux64"
    mkdir "$miniconda_dir/EupsBuildDir"
    ln -s "$workdir/EupsBuildDir/Linux64" "$miniconda_dir/EupsBuildDir"
  fi

  popd

  cleaner_thread "${lsst_home}/${miniconda_dir}" &

  source "${lsst_home}"/loadLSST.bash
  (
    eups distrib install hscPipe "${hscpipe_ver}"
  )

  rm -rf "${lsst_home}/${miniconda_dir}/EupsBuildDir"

  strip_hack_from_gcc

  # install bashrc
  cat "$(dirname "$0")"/rsrc/bashrc.in |
    sed s$'\xff'@prefix@$'\xff'"$prefix"$'\xff'g |
    sed s$'\xff'@lsst_home@$'\xff'"$LSST_HOME"$'\xff'g |
    sed s$'\xff'@hscpipe_ver@$'\xff'"$hscpipe_ver"$'\xff'g \
    > "$prefix"/bashrc

  # setup-eups() in bashrc needs $prefix/bin/check-requisites-hscPipe-${hscpipe_ver},
  # which will be created by post_build.sh. For users who won't run
  # post_build.sh, we place an empty exe there

  echo "int main(){ return 0; }" > "$workdir"/check-requisites.c
  gcc -O3 "$workdir"/check-requisites.c \
    -o "${prefix}/bin/check-requisites-hscPipe-${hscpipe_ver}"

  # Place create-rootdir.sh in bin/
  cat "$(dirname "$0")"/rsrc/create-rootdir.sh > "$prefix"/bin/create-rootdir.sh
  chmod a+x "$prefix"/bin/create-rootdir.sh

  # remove ".tests" directories
  find "${prefix}" -type d -name ".tests" -exec rm -rf {} +
)

cleaner_thread()
(
  cd "$1"
  while [[ -e EupsBuildDir ]]
  do
    sleep 60
    dirs=($(ls -d -t -1 EupsBuildDir/Linux64/* 2> /dev/null))
    # remove all the dirs except the newest ones
    for((i = 3; i < ${#dirs[@]}; ++i))
    do
      rm -rf "${dirs[i]}"
    done
  done

  echo "EupsBuildDir cleaner died. (This is not an error)"
)

main
