#!/bin/sh

set -e

DEB_VERSION_UPSTREAM=$(dpkg-parsechangelog -SVersion | sed -e 's/-[^-]*$//' -e 's/^[0-9]*://')
UPSTREAM_VERSION=${GBP_UPSTREAM_VERSION:-$DEB_VERSION_UPSTREAM}

ORIG_TARBALL=$(realpath "../jruby_${UPSTREAM_VERSION}.orig-rubygems.tar.xz")
GEM_TEMP=$(mktemp -d rubygems.XXXXXX)
WORKING_DIR="${PWD}"

cleanup() {
    cd "${WORKING_DIR}"
    rm -rf "${GEM_TEMP}"
}

trap "cleanup" EXIT TERM INT

if [ -e "$ORIG_TARBALL" ]; then
    echo "existing rubygems-orig tarball found at ${ORIG_TARBALL}, aborting!"
    exit 1
fi

cd "$GEM_TEMP" > /dev/null
mkdir info gems

awk '/^default_gems =/{flag=1;next}/^\s*#/{next}/^]/{flag=0}flag' ../lib/pom.rb | sed "s/\s\+\['\(.*\)', '\([0-9a-z\.]\+\)'.*/\1 \2/" \
| while read -r gem ver; do
    echo "downloading ${gem}-${ver}"
    url=""
    if wget -q "https://rubygems.org/info/${gem}" -O "info/${gem}"; then
        # check if we have a java platform version available
        if grep -o "^[^-]\S\+" "info/${gem}" | grep -qF "${ver}-java"; then
            url="https://rubygems.org/gems/${gem}-${ver}-java.gem"
        elif grep -o "^[^-]\S\+" "info/${gem}" | grep -qF "${ver}"; then
            url="https://rubygems.org/gems/${gem}-${ver}.gem"
        fi
    fi
    if [ -z "$url" ]; then
        # not on rubygems.org, so try to get from maven.org
        url="https://repo1.maven.org/maven2/rubygems/${gem}/${ver}/${gem}-${ver}.gem"
    fi
    echo "  from ${url}"
    mkdir -p "gems/${gem}/${ver}"
    wget -q "$url" -O "gems/${gem}/${ver}/${gem}-${ver}.gem"
done

# create the tarballs
cd gems > /dev/null
tar caf "$ORIG_TARBALL" .

echo "created component tarball at: ${ORIG_TARBALL}"

cd "$WORKING_DIR"
pristine-tar commit "$ORIG_TARBALL"

echo "all done!"
