#!/usr/bin/env bash

INCOMING_ARGS=("$@")

JAVA_OPTIONS="-Xmx512m"

if [ -d '${install.dir}' ]; then
    # shellcheck disable=SC2154
    OPENNMS_HOME="${install.dir}"
fi

[ -z "$RUNAS" ] && RUNAS=opennms

if [ -f "$OPENNMS_HOME/etc/opennms.conf" ]; then
	# shellcheck disable=SC1090,SC1091
	. "$OPENNMS_HOME/etc/opennms.conf"
fi

RUNUSER="$(command -v runuser 2>/dev/null || which runuser 2>/dev/null || :)"
myuser="$(id -u -n)"
if [ "$myuser" != "$RUNAS" ]; then
	if [ "$myuser" = "root" ] && [ -x "$RUNUSER" ]; then
		echo "WARNING: relaunching as $RUNAS" >&2
		_cmd=("$RUNUSER" "-u" "$RUNAS" -- "$0" "${INCOMING_ARGS[@]}");
		exec "${_cmd[@]}"
	fi
	echo "ERROR: you should run this script as ${RUNAS}, not '${myuser}'." >&2
    echo "       To correct this, try 'sudo -u ${RUNAS} $0 $@'" >&2
    echo "       If you wish for OpenNMS to run as ${myuser} instead," >&2
    echo "       create or edit ${OPENNMS_HOME}/etc/opennms.conf and set 'RUNAS=${myuser}'." >&2
	exit 4 # According to LSB: 4 - user had insufficient privileges
fi

APP_CLASS=org.opennms.upgrade.support.Upgrade
# shellcheck disable=SC2086
exec "$OPENNMS_HOME/bin/runjava" -r -- $JAVA_OPTIONS \
	-Dopennms.home="$OPENNMS_HOME" \
	-Dlog4j.configurationFile="$OPENNMS_HOME"/etc/log4j2-tools.xml \
	-Dopennms.manager.class="$APP_CLASS" \
	-jar "$OPENNMS_HOME/lib/opennms_bootstrap.jar" "$@"
