#!/bin/bash

# h4 script to dump a systemd unit's journal.
# Requires root privileges.
# We also cause the respective service to dump its threads, deadlocks and heap
# info on stdout (which is captured in the journal).
# We dump the journal to outputdir, so it can be included in support bundles.
#
# Usage:
#     dumpjournal svc1,svc2...svcN /output/folder
# Where svc is one of cloud, replicator, manager, lwdproxy, h4postgresql, hbrsrv, h4postgresql, h4sysboot.

if [ $# -lt 2 ]; then
    /usr/bin/echo "Usage: $0 svc1,svc2...svcN outputdir" 1>&2
    exit 1
fi

# the last argument is output dir
dir=${@: -1}

# make sure the services are valid
for arg in "${@:1:$#-1}"
do
    case "$arg" in
        cloud | manager | replicator | tunnel | lwdproxy)

          PID=$(/usr/bin/systemctl -p MainPID show "$arg" | /usr/bin/awk -F = '{print $2}')
          /usr/bin/kill -3 "$PID"
          /usr/bin/sleep 0.5
          ;;

       h4postgresql | hbrsrv | h4sysboot)
          ;;
       *)
          echo "Invalid service name: $arg"
          exit 9
    esac

    /usr/bin/journalctl --utc -u "$arg" > "$dir/$arg.log"
    /usr/bin/chown h4:h4 "$dir/$arg.log"
done

/usr/bin/journalctl --utc -t kernel > "$dir/kernel.log"
/usr/bin/chown h4:h4 "$dir/kernel.log"
