#!/usr/bin/env bash

set -euo pipefail

script_home="$(cd "$(dirname "$0")" && pwd)"
top="$script_home/../.."
cd "$top"  # Always run from the top level of the tree

usage() {
    echo "Usage: $(basename "$0") [REF]"
}

lein-pprint() {
    lein with-profile dev,ci pprint "$@" | sed -e 's/^"//' -e 's/"$//'
}

PDB_NO_PUPPETSERVER_INSTALL="${PDB_NO_PUPPETSERVER_INSTALL:-}"

if test -z "$(type -t bundler)"; then
    cat 2>&1 <<-EOS
	Ruby bundler does not appear to be available.
	Please install it via "gem install --user-install bundler" or similar.
	EOS
    exit 2
fi

set -x

rm -f ext/test-conf/puppetserver-ref-requested ext/test-conf/puppetserver-dep

case "$#" in
    0)
        pupsrv_ref="$(cat ext/test-conf/puppetserver-ref-default)"
        ;;
    1)
        pupsrv_ref="$1"
        echo "$pupsrv_ref" > ext/test-conf/puppetserver-ref-requested
        ;;
    *)
        usage 1>&2
        exit 2
esac

if test -d puppetserver; then
   git -C puppetserver checkout "$pupsrv_ref"
   git -C puppetserver clean -fdx
else
   git clone --depth 10 -b "$pupsrv_ref" https://github.com/puppetlabs/puppetserver
fi

(export PUPPETSERVER_HEAP_SIZE=1G
 cd puppetserver
 # If we're not testing against the git tree (say in jenkins), don't install.
 if test -z "$PDB_NO_PUPPETSERVER_INSTALL"; then
     lein install
 fi
 dep_ver="$(lein-pprint :version)"
 echo "$dep_ver" > "$top/ext/test-conf/puppetserver-dep")

lein install-gems
