#!/usr/bin/env bash

INCOMING_ARGS=("$@")

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

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

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

# if we have ulimit, attempt to raise it
# shellcheck disable=SC3045
if ulimit -a >/dev/null 2>&1; then
	for SIZE in 1024 2048 4096 8192 16384 20480; do
		CURRENT="$(ulimit -n)"
		if [ "$CURRENT" = "unlimited" ]; then
			break
		fi
		if [ "$CURRENT" -lt "$SIZE" ]; then
			if ulimit -n "$SIZE" >/dev/null 2>&1; then
				break
			fi
		fi
	done
fi

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

OPTIONS=""
for opt in $ADDITIONAL_MANAGER_OPTIONS; do
	case "$opt" in
		-Dcom.sun.management.jmxremote.*)
			# skip this option for the installer
			;;
		-Dopennms.poller.server.serverHost*)
			# skip this option for the installer
			;;
		*)
			OPTIONS="$OPTIONS $opt"
			;;
	esac
done

RUN_FIX_KARAF=false;
for i in ${@}; do
        if [ "$i" != "--help" -a "$i" != "-h" ]; then
                RUN_FIX_KARAF=true;
        else
                RUN_FIX_KARAF=false;
        fi
done
if [ "$RUN_FIX_KARAF" = true ]; then
        echo "Invoking fix-karaf-setup.sh script..."
        "$OPENNMS_BINDIR"/fix-karaf-setup.sh --yes
fi

# shellcheck disable=SC2086
exec "$OPENNMS_BINDIR"/runjava -r -- \
	$OPTIONS \
	-Dopennms.home="$OPENNMS_HOME" \
	-Dlog4j.configurationFile="$OPENNMS_HOME"/etc/log4j2-tools.xml \
	-cp "$OPENNMS_HOME/lib/opennms_bootstrap.jar" \
	org.opennms.bootstrap.InstallerBootstrap \
	"$@"
