#!/usr/bin/env bash

set -e

# Note: the variables here may look generic, but are currently
# exported by the puppet packaging scripts.  For example, even though
# they may look like it, JAVA_BIN and JAVA_ARGS are not upstream java
# variables (like JAVA_OPTS), but are set and exported by puppet.  And
# the USER variable here is not the bash variable of the same name,
# but is shadowing/clobbering it.  Most/all of these should be renamed
# to something less generic like PDB_CONFIG_FILE, or better yet (for
# that particular one), perhaps puppetdb should just support the
# variable itself.

cli_defaults=${INSTALL_DIR}/cli/cli-defaults.sh
CLASSPATH=${INSTALL_DIR}/puppetdb.jar

if [ -e "$cli_defaults" ]; then
  . "$cli_defaults"
  if [ $? -ne 0 ]; then
    echo "Unable to initialize cli defaults, failing start." 1>&2
    exit 1
  fi
fi

cmd=($(printf "%q %s -Dlogappender=STDOUT -cp %q clojure.main -m puppetlabs.puppetdb.core upgrade -c %q" \
     "$JAVA_BIN" "$JAVA_ARGS" "$CLASSPATH" "$CONFIG"))

if test "$(id -un)" = "$USER"; then
    exec "${cmd[@]}" "$@"
else
    exec su -s /bin/sh "$USER" -c "${cmd[*]} ${*}"
fi
