#!/bin/sh

set -eu

CWD="$PWD"
DEB_VERSION_UPSTREAM=$(dpkg-parsechangelog -SVersion | sed -e 's/-[^-]*$//' -e 's/^[0-9]*://')

# only bundle these gems
BUNDLE_GEMS=concurrent-ruby

cat resources/ext/build-scripts/jruby-gem-list.txt resources/ext/build-scripts/mri-gem-list-no-dependencies.txt |\
    grep "^${BUNDLE_GEMS}\s" |\
    while read -r gem ver; do
        # make temp directories
        GEM_TEMP_DOWNLOAD=$(mktemp -q -d /tmp/rubygem.XXXXXX)
        GEM_TEMP_INSTALLDIR=$(mktemp -q -d "/tmp/${gem}.XXXXXX")
        # download from rubygems.org
        url="https://api.rubygems.org/gems/${gem}-${ver}.gem"
        wget "$url" -O "${GEM_TEMP_DOWNLOAD}/${gem}-${ver}.gem"
        # install the gem and cleanup
        gem install --local --no-document --install-dir "${GEM_TEMP_INSTALLDIR}" "${GEM_TEMP_DOWNLOAD}/${gem}-${ver}.gem"
        rm -rf "${GEM_TEMP_INSTALLDIR}/cache"
        # pack installed gem into tarball
        cd "$GEM_TEMP_INSTALLDIR"
        tar -caf "${CWD}/../puppetserver_${DEB_VERSION_UPSTREAM}.orig-rubygem-${gem}.tar.xz" .
        echo "prepared ../puppetserver_${DEB_VERSION_UPSTREAM}.orig-rubygem-${gem}.tar.xz"
        cd "$CWD"
        # cleanup temp directories
        rm -rf "$GEM_TEMP_DOWNLOAD"
        rm -rf "$GEM_TEMP_INSTALLDIR"
    done
