1#!/bin/bash
2# Copyright (c) Meta Platforms, Inc. and affiliates.
3#
4# This source code is licensed under the MIT license found in the
5# LICENSE file in the root directory of this source tree.
6
7set -e
8
9if [ "$VERBOSE" = 1 ]; then
10    set -x
11fi
12
13case $(sed --help 2>&1) in
14  *GNU*) sed_i () { sed -i "$@"; };;
15  *) sed_i () { sed -i '' "$@"; };;
16esac
17
18SCRIPTS="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
19ROOT="$(dirname "$SCRIPTS")"
20
21die() {
22    echo "ERROR: $*" >&2
23    exit 1
24}
25
26if [ $# -eq 1 ]; then
27    VERSION=$1
28else
29    VERSION=$(ruby --version | cut -d' ' -f2 | cut -dp -f1)
30fi
31
32if [ -z "$VERSION" ]; then
33    die "Please provide an installed/usable Ruby version"
34fi
35echo "Setting Ruby version to: $VERSION"
36
37cd "$ROOT" || die "Failed to change to $ROOT"
38
39# do this first, so rbenv/rvm will automatically pick the desired version
40echo "$VERSION" > .ruby-version
41
42# make sure we're using it
43CURRENT_VERSION=$(ruby --version | cut -d' ' -f2 | cut -dp -f1)
44if [ -z "$CURRENT_VERSION" ]; then
45    # rbenv/rvm uses shims, the commands do exist, but do not return a version if misconfigured
46    die "Missing usable ruby, check your installation"
47elif [ "$VERSION" != "$CURRENT_VERSION" ]; then
48    die "Plese use the ruby version you are trying to set: $VERSION ('$CURRENT_VERSION' in use)"
49fi
50
51echo "$VERSION" > template/_ruby-version
52
53sed_i -e "s/^\(ruby '\)[^']*\('.*\)$/\1$VERSION\2/" Gemfile
54sed_i -e "s/^\(ruby '\)[^']*\('.*\)$/\1$VERSION\2/" template/Gemfile
55
56rm -f Gemfile.lock
57
58export BUNDLE_APP_CONFIG="$ROOT/.bundle"
59cp "$BUNDLE_APP_CONFIG/"* template/_bundle # sync!
60
61bundle lock
62
63git add \
64    .ruby-version \
65    Gemfile \
66    Gemfile.lock \
67    template/_ruby-version \
68    template/Gemfile
69