# Require $prefix, $workdir, $gcc_src
# Optional $native ('True' or 'False')
install_gcc()
(
  set -e
  [[ -e "$prefix"/bin/gcc ]] && exit 0

  [[ "$workdir" = */hscpipe_build_dir ]] || exit 1
  rm -rf "$workdir"; mkdir -p "$workdir"; pushd "$workdir"

  curl -L "$gcc_src" | tar -xJf -

  cd *
  src_dir="$PWD"

  ./contrib/download_prerequisites

  mkdir ../temp
  cd ../temp

  "$src_dir"/configure \
    --prefix="$prefix" \
    --disable-multilib \
    --enable-languages="c,c++,fortran"

  make
  make install

  # Install cc & c++ in order to let them hide system cc & c++

  if [[ ! -e "$prefix/bin/cc" ]]
  then
    ln "$prefix/bin/gcc" "$prefix/bin/cc"
  fi

  if [[ ! -e "$prefix/bin/c++" ]]
  then
    ln "$prefix/bin/g++" "$prefix/bin/c++"
  fi

  # Replace gcc (etc) with bash scripts
  # that exec gcc (etc) with "-Wl,-rpath" option.

  local lang
  for lang in gcc g++ gfortran
  do
    local proto="$prefix/bin/${lang}-prototype"
    ln "$prefix/bin/${lang}" "${proto}"
    local exe
    for exe in "$prefix/bin/"*
    do
      if [[ "${exe}" != "${proto}" && "${exe}" -ef "${proto}" ]]
      then
        mv "${exe}" "${exe}-raw"
        cat > "${exe}" << __eof__
#!/bin/bash
orgIFS="\$IFS"
IFS=":"
runpaths=(\$LD_RUN_PATH $prefix/lib64 $prefix/lib)
IFS="\$orgIFS"

rpath=":"
for elem in "\${runpaths[@]}"
do
  if [[ -z "\$elem" ]]
  then
    continue
  fi
  if [[ "\$rpath" != *":\$elem:"* ]]
  then
    rpath+="\$elem:"
  fi
done

rpath="\${rpath#:}"
rpath="\${rpath%:}"

# BEGIN GCC_HACK_DISABLE_MARCH_NATIVE
if [[ "$native" != "True" ]]
then
  args=()
  for i in "\$@"
  do
    if [[ "\$i" != "-march=native" ]]
    then
      args+=("\$i")
    fi
  done
  exec -a "\$0" ${exe}-raw "\${args[@]}" -Wl,-rpath,"\$rpath"
fi
# END GCC_HACK_DISABLE_MARCH_NATIVE
exec -a "\$0" ${exe}-raw "\$@" -Wl,-rpath,"\$rpath"
__eof__
        chmod a+x "${exe}"
      fi
    done
    rm -f "${proto}"
  done
)

# Require $prefix
strip_hack_from_gcc()
(
  set -e

  cd "$prefix/bin"
  for exe in *
  do
    if grep -q 'GCC_HACK_DISABLE_MARCH_NATIVE' "${exe}"
    then
      mv "${exe}" "${exe}~"
      cat "${exe}~" |
        sed -n '/# BEGIN GCC_HACK_DISABLE_MARCH_NATIVE/,/# END GCC_HACK_DISABLE_MARCH_NATIVE/ d; p' \
        > "${exe}"
      chmod a+x "${exe}"
      rm -f "${exe}~"
    fi
  done
)

