#!/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 -e

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

prepare_gem_home() {
    for d in gems specifications; do
        if [ ! -d "${PUPPETSERVER_GEM_HOME}/${d}" ]; then
            mkdir -p "${PUPPETSERVER_GEM_HOME}/${d}"
        fi
    done
}

get_gem_version() {
    echo "$1" | grep -oP "[0-9\.]+(?=\.gemspec)"
}

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
"

for gemspec_path in $gemspec_search_paths; do
    spec=$(find "$gemspec_path" -type f -regex ".*/${gem}-[0-9\.]+\.gemspec")
    if [ -n "$spec" ]; then
        ver=$(get_gem_version "${spec}")
        prepare_gem_home
        cp "$spec" "${PUPPETSERVER_GEM_HOME}/specifications"
        # remove any reference to native mri extensions
        sed -i -e '/\s*s\.extensions =/d' "${PUPPETSERVER_GEM_HOME}/specifications/${gem}-${ver}.gemspec"
        gems_path=$(echo "${spec}" | sed -e 's,/specifications/,/gems/,' -e 's/\.gemspec$//' -e "s,^debian/${DEB_SOURCE},,")
        # gem being built
        if [ -e "debian/${DEB_SOURCE}/$gems_path" ]; then
            ln -s "/${gems_path}" "${PUPPETSERVER_GEM_HOME}/gems"
        # packaged gem
        elif [ -e "$gems_path" ]; then
            ln -s "${gems_path}" "${PUPPETSERVER_GEM_HOME}/gems"
        # 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}"
		exit 0
	fi
done

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