#!/usr/bin/env bash

set -e

RUBY_VERSION=2.4.4
RUBYGEMS_VERSION=2.7.6
LIBYAML_VERSION=0.1.7

openssl_version=$(PATH=/usr/local/opt/openssl/bin:${PATH} openssl version)
openssl_major_version=$(echo "${openssl_version}" | cut -f2 -d\ | cut -f1 -d.)
if [ "${openssl_major_version}" == 0 ]; then
  echo "OpenSSL version 1 or greater is required."
  echo "Currently available: ${openssl_version}"
  exit 1
fi

tar xzf "yaml-${LIBYAML_VERSION}.tar.gz"
(
  set -e
  cd "yaml-${LIBYAML_VERSION}"

  if [ "$(uname -m)" == "ppc64le" ]; then
    cp "${BOSH_COMPILE_TARGET}"/config/config.{guess,sub} ./tool
  fi

  CFLAGS='-fPIC' ./configure --prefix="${BOSH_INSTALL_TARGET}" --disable-shared
  make
  make install
)

tar xzf "ruby-${RUBY_VERSION}.tar.gz"
(
  set -e
  cd "ruby-${RUBY_VERSION}"

  if [ "$(uname -m)" == "ppc64le" ]; then
    cp "${BOSH_COMPILE_TARGET}"/config/config.{guess,sub} ./tool
  fi

  LDFLAGS="-Wl,-rpath -Wl,${BOSH_INSTALL_TARGET}" CFLAGS='-fPIC' ./configure --prefix="${BOSH_INSTALL_TARGET}" --disable-install-doc --with-opt-dir="/usr/local/opt/openssl:${BOSH_INSTALL_TARGET}" --without-gmp
  make
  make install
)

mkdir "${BOSH_INSTALL_TARGET}/bosh"
cp gemrc "${BOSH_INSTALL_TARGET}/bosh/gemrc"
cp compile.env "${BOSH_INSTALL_TARGET}/bosh/compile.env"
cp runtime.env "${BOSH_INSTALL_TARGET}/bosh/runtime.env"

source "${BOSH_INSTALL_TARGET}/bosh/runtime.env"

tar zxvf "rubygems-${RUBYGEMS_VERSION}.tgz"
(
  set -e
  cd "rubygems-${RUBYGEMS_VERSION}"

  if ! ruby setup.rb --no-ri --no-rdoc; then
    echo "Cannot install rubygems"
    exit 1
  fi
)

# We need to replace the shebang in the default binstubs generated by rubygems.
# As of rubygems 2.7.6 and ruby 2.4.4 they fixed a vulnerability with regards
# to path traversal and symlinks. The resulting fix uses the real path for the
# shebang which includes a checksum that is not constant across BOSH vms.  See
# https://blog.rubygems.org/2018/02/15/2.7.6-released.html for more details.
ruby overwrite_shebang.rb "${BOSH_INSTALL_TARGET}/bin/gem"
ruby overwrite_shebang.rb "${BOSH_INSTALL_TARGET}/bin/bundle"
