#!/bin/bash -e

# TODO: Review and if possible fix shellcheck errors.
# shellcheck disable=all

[ "${BASH_SOURCE[0]}" ] && SCRIPT_NAME="${BASH_SOURCE[0]}" || SCRIPT_NAME=$0
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_NAME")/.." && pwd -P)"

fftw_ver="3.3.11"
fftw_sha256="5630c24cdeb33b131612f7eb4b1a9934234754f9f388ff8617458d0be6f239a1"
fftw_pkg="fftw-${fftw_ver}.tar.gz"

source "${SCRIPT_DIR}"/common_vars.sh
source "${SCRIPT_DIR}"/tool_kit.sh
source "${SCRIPT_DIR}"/signal_trap.sh
source "${INSTALLDIR}"/toolchain.conf
source "${INSTALLDIR}"/toolchain.env

[ -f "${BUILDDIR}/setup_fftw" ] && rm "${BUILDDIR}/setup_fftw"

! [ -d "${BUILDDIR}" ] && mkdir -p "${BUILDDIR}"
cd "${BUILDDIR}"

case "$with_fftw" in
  __INSTALL__)
    echo "==================== Installing FFTW ===================="
    pkg_install_dir="${INSTALLDIR}/fftw-${fftw_ver}"
    install_lock_file="${pkg_install_dir}/install_successful"

    if verify_checksums "${install_lock_file}"; then
      echo "fftw-${fftw_ver} is already installed, skipping it."
    else
      retrieve_package "${fftw_sha256}" "${fftw_pkg}"
      echo "Installing from scratch into ${pkg_install_dir}"
      [ -d fftw-${fftw_ver} ] && rm -rf fftw-${fftw_ver}
      tar -xzf ${fftw_pkg}
      cd fftw-${fftw_ver}
      FFTW_FLAGS="--enable-openmp --disable-shared --enable-static"
      # fftw has mpi support but not compiled by default. so compile it if we build with mpi.
      # it will create a second library to link with if needed
      [ "${MPI_MODE}" != "no" ] && FFTW_FLAGS="--enable-mpi ${FFTW_FLAGS}"
      if [ "${TARGET_CPU}" = "native" ]; then
        if [ -f /proc/cpuinfo ]; then
          grep '\bavx\b' /proc/cpuinfo 1> /dev/null && FFTW_FLAGS="${FFTW_FLAGS} --enable-avx"
          grep '\bavx2\b' /proc/cpuinfo 1> /dev/null && FFTW_FLAGS="${FFTW_FLAGS} --enable-avx2"
          grep '\bavx512f\b' /proc/cpuinfo 1> /dev/null && FFTW_FLAGS="${FFTW_FLAGS} --enable-avx512"
          grep '\bsse2\b' /proc/cpuinfo 1> /dev/null && FFTW_FLAGS="${FFTW_FLAGS} --enable-sse2"
        fi
      fi
      ./configure CFLAGS="${CFLAGS} -std=c17" \
        --prefix=${pkg_install_dir} \
        --libdir="${pkg_install_dir}/lib" \
        ${FFTW_FLAGS} \
        > configure.log 2>&1 || tail_excerpt configure.log
      make -j $(get_nprocs) > make.log 2>&1 || tail_excerpt make.log
      make install > install.log 2>&1 || tail_excerpt install.log
      cd ..
      write_checksums "${install_lock_file}" "${SCRIPT_DIR}/stage3/$(basename ${SCRIPT_NAME})"
    fi
    ;;
  __SYSTEM__)
    echo "==================== Finding FFTW from system paths ===================="
    check_lib -lfftw3 "FFTW"
    check_lib -lfftw3_omp "FFTW"
    [ "${MPI_MODE}" != "no" ] && check_lib -lfftw3_mpi "FFTW"
    pkg_install_dir="$(dirname $(dirname $(find_in_paths "libfftw3.*" $LIB_PATHS)))"
    # Deal with the condition that libfftw3 is installed in "/usr/lib/x86_64-linux-gnu"
    if [[ "${pkg_install_dir}" == "/usr/lib"* ]]; then
      pkg_install_dir="/usr"
    fi
    ;;
  __DONTUSE__)
    # Nothing to do
    ;;
  *)
    echo "==================== Linking FFTW to user paths ===================="
    pkg_install_dir="$with_fftw"
    check_dir "${pkg_install_dir}/lib"
    check_dir "${pkg_install_dir}/include"
    ;;
esac
if [ "$with_fftw" != "__DONTUSE__" ]; then
  [ "$MPI_MODE" != "no" ] && FFTW_LIBS="-lfftw3_mpi "
  FFTW_LIBS+="-lfftw3 -lfftw3_omp"
  if [ "$with_fftw" != "__SYSTEM__" ]; then
    cat << EOF > "${BUILDDIR}/setup_fftw"
prepend_path LD_LIBRARY_PATH "${pkg_install_dir}/lib"
prepend_path LD_RUN_PATH "${pkg_install_dir}/lib"
prepend_path LIBRARY_PATH "${pkg_install_dir}/lib"
prepend_path PKG_CONFIG_PATH "${pkg_install_dir}/lib/pkgconfig"
prepend_path CMAKE_PREFIX_PATH "${pkg_install_dir}"
EOF
  fi
  # we may also want to cover FFT_SG
  cat << EOF >> "${BUILDDIR}/setup_fftw"
export FFTW_VER="${fftw_ver}"
export FFTW3_INCLUDES="-I${pkg_install_dir}/include"
export FFTW3_LIBS="${FFTW_LIBS}"
export FFTW_ROOT="${FFTW_ROOT:-${pkg_install_dir}}"
export FFTW3_ROOT="${FFTW_ROOT:-${pkg_install_dir}}"
EOF
  filter_setup "${BUILDDIR}/setup_fftw" "${SETUPFILE}"
fi
cd "${ROOTDIR}"

# ----------------------------------------------------------------------
# Suppress reporting of known leaks
# ----------------------------------------------------------------------
cat << EOF >> ${INSTALLDIR}/valgrind.supp
{
   <BuggyFFTW3>
   Memcheck:Addr32
   fun:cdot
   ...
   fun:invoke_solver
   fun:search0
}
EOF

load "${BUILDDIR}/setup_fftw"
write_toolchain_env "${INSTALLDIR}"

report_timing "fftw"
