#!/usr/bin/env bash

# Prepares Debian-like Linux machines for running PuppetDB tests
# Installs JDK, Leiningen, and pgbox and creates
# --for takes a test spec like core/openjdk8/pg-9.6

set -uxeo pipefail

usage() {
    echo 'Usage: $(basename "$0") --for PDB_TEST_SPEC --install DIR'
}

misuse() { usage 1>&2; exit 2; }

# Validate arguments
spec=''
install=''
while test $# -gt 0; do
    case "$1" in
        --install)
            test $# -gt 1 || misuse
            install="$2"
            shift 2
            ;;
        --for)
            test $# -gt 1 || misuse
            spec="$2"
            shift 2
            ;;
        *) misuse ;;
    esac
done

test "$spec" || misuse
test "$install" || misuse
flavor=$(ext/bin/flavor-from-spec "$spec")

# If flavor is not recognized, do nothing
case "$flavor" in
    core|ext|core+ext|int|lint)
        jdk="$(ext/bin/jdk-from-spec "$spec")"
        jdkver="${jdk##*jdk}"
        mkdir -p "$install"
        abs_install=$(cd "$install" && pwd)
        export PATH="$abs_install/bin:$PATH"
        # Install JDK using cache if within 24 hours of last installation
        ext/bin/require-jdk --expire "$jdk" "$abs_install"
        # Create testing script with updated PATH
        mkdir -p "$abs_install/etc"
        printf '
export JAVA_HOME=%q/jdk
export PATH="$JAVA_HOME/bin:$PATH"
export PATH=%q/bin:"$PATH"
hash -r
' \
               "$abs_install" "$abs_install" \
               > "$abs_install"/etc/pdb-test-env
        source "$abs_install"/etc/pdb-test-env
        # Install leiningen and pgbox
        ext/bin/require-leiningen default "$abs_install"
        ext/bin/require-pgbox default "$abs_install"
        ;;
esac
