#!/bin/sh
#
# Start OSGi runner in foreground for systemd integration.
#
# $Id$
#

export OSGI_PERFORM_REGROUP_BUNDLES="yes"

if test "$OSGI_RUNNER_CONFIG_INCLUDED" != iro4sAFb2zRYXpP9
then
    . /usr/share/osgi-runner/sh/load-config-include.sh
fi

if test "$1" = "--help" -o "$1" = "-h" -o "$1" = "help"
then
    echo "usage: /usr/sbin/osgi-runner-debug [--debug|--synchronous|--timeout <seconds>]"
    echo "       Start osgi-runner in the foreground for debugging."
    echo "       --debug shows debug output from org.clazzes.osgi.runner.Main."
    echo "       --synchronous starts bundles synchronously."
    echo "       --timeout specifies the timeout for synchronous mode in seconds."
    exit 0
fi

OSGI_PID=$(systemctl show -p MainPID osgi-runner.service | sed 's/MainPID=\([1-9][0-9]*\)/\1/p;d')

if test -n "$OSGI_PID"
then
    if ps -p $OSGI_PID > /dev/null 2>&1
    then
        echo "Cannot start osgi-runner in debug mode, because daemon is running with PID $OSGI_PID."
        exit 101
    else
        echo "osgi-runner process with PID $OSGI_PID does not exist, unknown daeomn state."
        exit 102
    fi
fi

echo '***** '"Will run the following command:"
if [ "$(id -un)" = "$OSGI_USER" -a "$(id -gn)" = "$OSGI_GROUP" ] ; then
  echo "$JAVA_EXE" -Dosgi.runner.etcPath="$OSGI_ETCDIR" $OSGI_OPTS -cp "${OSGI_BASE}/lib/"'*':"${OSGI_BASE}/drivers/"'*' org.clazzes.osgi.runner.Main $*
  echo '***** '"Output from osgi-runner follows..."
  exec "$JAVA_EXE" -Dosgi.runner.etcPath="$OSGI_ETCDIR" $OSGI_OPTS -cp "${OSGI_BASE}/lib/"'*':"${OSGI_BASE}/drivers/"'*' org.clazzes.osgi.runner.Main $*
else
  echo sudo -u $OSGI_USER -g $OSGI_GROUP "$JAVA_EXE" -Dosgi.runner.etcPath="$OSGI_ETCDIR" $OSGI_OPTS -cp "${OSGI_BASE}/lib/"'*':"${OSGI_BASE}/drivers/"'*' org.clazzes.osgi.runner.Main $*
  echo '***** '"Output from osgi-runner follows..."
  exec sudo -u $OSGI_USER -g $OSGI_GROUP "$JAVA_EXE" -Dosgi.runner.etcPath="$OSGI_ETCDIR" $OSGI_OPTS -cp "${OSGI_BASE}/lib/"'*':"${OSGI_BASE}/drivers/"'*' org.clazzes.osgi.runner.Main $*
fi

