#!/usr/bin/env bash

set -euo pipefail
IFS=$'\n\t'

mkdir -p ~/.gem/
temp_file=$(mktemp)

# Revert change the credentials file
function revert_gem_cred_switch {
  mv "$temp_file" ~/.gem/credentials
}

if [[ -f ~/.gem/credentials ]]; then
  echo "Temporarily moving existing credentials to $temp_file"
  mv ~/.gem/credentials "$temp_file"
  trap revert_gem_cred_switch EXIT
fi

cat <<EOD > ~/.gem/credentials
---
:rubygems_api_key: $RUBYGEMS_API_KEY
EOD
chmod 600 ~/.gem/credentials

set -x

bundle install
bundle exec rake build
ls pkg/*.gem | xargs -n 1 gem push
