#!/bin/sh

set -e

DEB_VERSION_UPSTREAM=$(dpkg-parsechangelog -SVersion | sed -e 's/-[^-]*$//' -e 's/^[0-9]*://')
GEM_TEMP=$(mktemp -q -d rubygems.XXXXXX)

while read -r grp gem ver; do
    mkdir -p "${GEM_TEMP}/${grp}"
    if [ "$gem" = "jruby-readline" ]; then
        # not available on rubygems.org, for some reason
        url="https://repo1.maven.org/maven2/rubygems/${gem}/${ver}/${gem}-${ver}.gem"
    else
        url="https://api.rubygems.org/gems/${gem}-${ver}.gem"
    fi
    wget "$url" -O "${GEM_TEMP}/${grp}/${gem}-${ver}.gem"
done < debian/gem-list.txt

# create the tarballs
cd "${GEM_TEMP}/default"
tar caf "../../../jruby_${DEB_VERSION_UPSTREAM}.orig-rubygems-default.tar.xz" .

cd ../..
rm -rf "$GEM_TEMP"
