#!/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/dist.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()
(
  #
  # make the package portable
  #

  export PATH="$path"
  build_patchelf
  export PATH="$workdir/bin:$path"

  unlock_dir
  recreate_link
  recreate_elf
  lock_dir

  #
  # Save names of system libraries that this package
  # depends on
  #
  find_requisites

  #
  # Save names of text files that must be modified
  # in installation
  #
  find_modificanda

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

  chmod a+x "$prefix"/install.sh

  echo "untouched" > "${prefix}/.install.state"

  #
  # Place README.md &c.
  #
  for name in README.md
  do
    # don't use 'cp' so's not to copy permissions
    cat "$(dirname "$0")"/rsrc/"$name" \
      > "$prefix"/"$name"
  done

  cat "$(dirname "$0")"/rsrc/recompile-mpich.sh.in |
    sed s$'\xff'@eups_pkgroot_base_url@$'\xff'"$eups_pkgroot_base_url"$'\xff'g \
    > "$prefix"/recompile-mpich.sh

  chmod a+x "$prefix"/recompile-mpich.sh
)

main
