#!/bin/sh
#
# Dump core file and collect more information about crashed process
# <http://man7.org/linux/man-pages/man5/core.5.html>
#
[ -n "${BASE:-}" ] || BASE='/var/spool/univention-crash-report'

if [ -z "${1:-}" ]
then
	install -o 0 -g 0 -m 0700 -d "$BASE"
	echo "|$(readlink -f "$0") %u %g %p %s %e" >/proc/sys/kernel/core_pattern
	exit 0
fi

user="$1"
group="$2"
pid="$3"
signal="$4"
cmd="$5"

exe="$(readlink -f "/proc/$pid/exe")"

time="$(date --utc +'%F_%T')"
base="${BASE}/${time}_${user}_${group}-${signal}"
exec >"${base}.log" 2>&1
set -x

{
	echo "$cmd"
	cat "/proc/$pid/cmdline"
} >"${base}.cmd"
cp "/proc/$pid/environ" "${base}.env"
cp "/proc/$pid/maps" "${base}.maps"
ps www -p "$pid" >"${base}.ps"
lsof -n -p "$pid" >"${base}.lsof"
[ -t 0 ] ||
	cat >"${base}.core"
exec </dev/null

if pkg=$(dpkg -S "$exe")
then
	apt-cache depends --no-recommends --no-suggests --no-conflicts --no-breaks --no-replaces --no-enhances --installed --recurse "${pkg%%:*}" |
		grep '^[^ <]' |
		sort -u >"${base}.dpkg-S"
elif ldd "$exe" >"${base}.ldd"
then
	while read -r line
	do
		for arg in $line
		do
			[ -f "$arg" ] || continue
			dpkg -S "$arg"
		done
	done <"${base}.ldd" >"${base}.dpkg-S"
fi

find "/proc/$pid/map_files" -type l -printf '%l\0' |
	sort -z -u |
	xargs -0n1 dpkg-query -S >>"${base}.dpkg-S"

cut -d: -f1 <"${base}.dpkg-S" |
	sort -u |
	xargs dpkg-query -W >"${base}.dpkg-W"

# vim:set backupcopy=auto:
