#!/usr/bin/env bash

restartfile="/var/puppetlabs/puppetdb/data/restartcounter"
cli_defaults=${INSTALL_DIR}/cli/cli-defaults.sh

if [ ! -e "${INSTALL_DIR}/ezbake-functions.sh" ]; then
    echo "Unable to find ${INSTALL_DIR}/ezbake-functions.sh script, failing start." 1>&2
    exit 1
fi

. "${INSTALL_DIR}/ezbake-functions.sh"

init_restart_file "$restartfile" || exit $?

if !(echo "${@}" | grep -e "--debug" -q)
then
    LOG_APPENDER="-Dlogappender=STDOUT"
fi

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

COMMAND="${JAVA_BIN} ${JAVA_ARGS} ${LOG_APPENDER} \
         -cp "$CLASSPATH" \
         clojure.main -m puppetlabs.puppetdb.cli.services \
         --config ${CONFIG} --bootstrap-config ${BOOTSTRAP_CONFIG} \
         --restart-file "${restartfile}" \
         ${TK_ARGS} \
         ${@}"

pushd "${INSTALL_DIR}" &> /dev/null
if [ "$EUID" = "0" ] && command -v runuser &> /dev/null; then
  runuser "${USER}" -s /usr/bin/env bash -c "$COMMAND"
elif [ "$EUID" = "$(id -u ${USER})" ]; then
  /usr/bin/env bash -c "$COMMAND"
elif command -v sudo &> /dev/null; then
  sudo -H -u "${USER}" $COMMAND
else
  su "${USER}" -s /usr/bin/env bash -c "$COMMAND"
fi
popd &> /dev/null
