#!/bin/sh
#
# Dump OSGi runner under systemd control.
#
# $Id$
#

export OSGI_PERFORM_REGROUP_BUNDLES="no"

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

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

if test "$1" = "--help" -o "$1" = "-h" -o "$1" = "help"
then
    echo "usage: /usr/sbin/osgi-runner-dump"
    echo "       Exports a thread dump and a snapshot of osgi.log to"
    echo "       the dump directory $OSGI_DUMPDIR"
    echo "       This directory might be configured in /etc/default/osgi-runner"
    echo "       by setting the variable OSGI_DUMPDIR."
    exit 0
fi
    
echo "Dumping for osgi-runner logs to $OSGI_DUMPDIR..."
tag=$(date +%Y%m%d-%H%M%S)
if test -n "$OSGI_PID"
then
    if ps -p $OSGI_PID > /dev/null 2>&1
    then
        echo "Performing kill -3 $OSGI_PID"
        iso_rx='s/^([0-9]{4,4})-([0-9]{2,2})-([0-9]{2,2})T([0-9]{2,2}):([0-9]{2,2}):([0-9]{2,2}).*$/\1\2\3\4\5\6/p;d'
        timestamp=$(date -Iseconds --utc | sed -E $iso_rx)
        kill -3 $OSGI_PID
        echo "Creating $OSGI_DUMPDIR/$tag-osgi.log.gz"
        gzip -c -9 $OSGI_LOGDIR/osgi.log > $OSGI_DUMPDIR/$tag-osgi.log.gz

        while test  $timestamp -le $(journalctl -u osgi-runner.service --utc -n 1 -o short-iso | sed -E $iso_rx)
        do
            echo "Waiting for systemd journal to be filled with thread dump..."
            timestamp=$(date -Iseconds --utc | sed -E $iso_rx)
            sleep 1
        done
        echo "Creating $OSGI_DUMPDIR/$tag-journal.log.gz"
        journalctl -u osgi-runner.service -o short-precise | gzip -c -9 > $OSGI_DUMPDIR/$tag-journal.log.gz
    else
        echo "osgi-runner procaees with PID $OSGI_PID does not exist."
        exit 1
    fi
else
    echo "Cannot determine osgi-runner PID, service does not seem to be running."
    exit 1
fi
