#!/bin/sh

# This is a helper script for source packages to build binary packages that
# integrate gems into the isolated jruby environment of puppetserver.
# It uses symlinks to avoid the need to embed additional copies of the gems.

set -eu

gem=$1

DEB_SOURCE=$(dpkg-parsechangelog -SSource)
PUPPETSERVER_GEM_HOME=${PUPPETSERVER_GEM_HOME:-debian/${DEB_SOURCE}-puppetserver/usr/lib/puppetserver/vendored-jruby-gems}

gemspec_search_paths="
debian/${DEB_SOURCE}/usr/share/rubygems-integration/all/specifications
/usr/lib/${DEB_HOST_MULTIARCH}/rubygems-integration/*/specifications
/usr/share/rubygems-integration/all/specifications
"

mkdir -p "${PUPPETSERVER_GEM_HOME}/gems"
mkdir -p "${PUPPETSERVER_GEM_HOME}/specifications"

for gemspec_path in $gemspec_search_paths; do
    [ -d "$gemspec_path" ] || continue;
    spec=$(find "$gemspec_path" -type f -regex ".*/${gem}-[0-9\.]+\.gemspec")
    if [ -n "$spec" ]; then
        ver=$(echo "$spec" | grep -oP "[0-9\.]+(?=\.gemspec)")
        gems_path=$(echo "${spec}" | sed -e 's,/specifications/,/gems/,' -e 's/\.gemspec$//' -e "s,^debian/${DEB_SOURCE},,")
        # symlink the gemspec
        ln -s "$spec" "${PUPPETSERVER_GEM_HOME}/specifications"
        # handle gem being built
        if [ -e "debian/${DEB_SOURCE}/$gems_path" ]; then
            ln -s "/${gems_path}" "${PUPPETSERVER_GEM_HOME}/gems"
        # handle packaged gem
        elif [ -e "$gems_path" ]; then
            ln -s "${gems_path}" "${PUPPETSERVER_GEM_HOME}/gems"
        # handle packaged ruby library with included gemspec
        elif [ -e "/usr/lib/ruby/vendor_ruby/${gem}.rb" ]; then
            mkdir -p "${PUPPETSERVER_GEM_HOME}/gems/${gem}-${ver}/lib"
            for f in /usr/lib/ruby/vendor_ruby/"${gem}"*.rb; do
                ln -s "/usr/lib/ruby/vendor_ruby/$(basename "$f")" "${PUPPETSERVER_GEM_HOME}/gems/${gem}-${ver}/lib"
            done
            ln -s "/usr/lib/ruby/vendor_ruby/${gem}" "${PUPPETSERVER_GEM_HOME}/gems/${gem}-${ver}/lib"
		else
			echo "Error: unable to find the gem files for ${spec}"
			exit 1
		fi
		echo "Installed ${gem}-${ver} from ${spec}"
		exit 0
	fi
done

echo "Error: gemspec for '${gem}' could not be found on the system! Is the package installed?"
exit 1
