#!/bin/bash

set -eo pipefail

prefix=$(.buildkite/tools/sorbet-version-prefix.sh)

pushd gems/sorbet-runtime

echo "--- setup :ruby:"
eval "$(rbenv init -)"

runtime_versions=(3.3.12 3.4.9)

for runtime_version in "${runtime_versions[@]}"; do
  # Only uncomment this to iterate on something. Uncommenting this will make
  # all builds needlessly slower.
  # Prefer updating sorbet-build-image to pre-install the Ruby version.

  # rbenv install --skip-existing "$runtime_version"

  rbenv shell "$runtime_version"
  rbenv exec bundle config set path 'vendor/bundle'
  rbenv exec bundle install
done

for runtime_version in "${runtime_versions[@]}"; do
  rbenv shell "$runtime_version"

  rbenv exec ruby --version

  failed=

  echo "+++ rubocop ($runtime_version)"
  if ! rbenv exec bundle exec rake rubocop; then
    failed=1
  fi

  echo "+++ tests ($runtime_version)"
  if ! rbenv exec bundle exec rake test; then
    failed=1
  fi

  pushd test/wholesome

  rbenv exec bundle config set path 'vendor/bundle'
  rbenv exec bundle install

  if ! rbenv exec bundle exec rake test; then
    failed=1
  fi

  popd

  if [ "$failed" != "" ]; then
    exit 1
  fi
done

echo "--- build"
git_commit_count=$(git rev-list --count HEAD)
release_version="${prefix}.${git_commit_count}"
sed -i.bak "s/0\\.0\\.0/${release_version}/" sorbet-runtime.gemspec
gem build sorbet-runtime.gemspec
popd

rm -rf _out_
mkdir -p _out_/gems/
cp gems/sorbet-runtime/sorbet-runtime-*.gem _out_/gems/
