#!/bin/sh
#
# This script is meant to be run once at system startup after abrtd is up
# and running. It moves all vmcore directories in /var/crash
# (which are presumably created by kdump) to abrtd spool directory.
#
# The goal is to let abrtd notice and process them as new problem data dirs.
#

cd /var/crash 2>/dev/null || exit 0

# Wait for abrtd to start. Give it at least 1 second to initialize.
i=10
while ! pidof abrtd >/dev/null; do
	if test $((i--)) = 0; then
		exit 1
	fi
	sleep 1
done
sleep 1

umask 077

CopyVMcore=`sed -n '/^CopyVMcore[ \t]*=/ s/.*=[ \t]*//p' /etc/abrt/abrt-harvest-vmcore.conf 2>/dev/null`

move_core=false
if test x"$CopyVMcore" = x"no" || test x"$CopyVMcore" = x"0"; then
	move_core=true
fi

for d in *; do
	test -d "$d" || continue
	test -f "$d/vmcore" || continue

	dst="/var/spool/abrt/vmcore-$d"

	# Did we already copy it last time we booted?
	test -d "$dst" && continue
	test -d "$dst.new" && continue

	# Let abrtd know what type of problem it is:
	printf 'vmcore' >"$d/analyzer"
	printf 'vmcore' >"$d/type"
	printf 'kernel' >"$d/component"
	printf '%s' "`date '+%s'`" >"$d/time"
	printf '0' >"$d/uid"
	# TODO: need to generate *real* UUID,
	# one which has a real chance of catching dups!
	# This one generates different hashes even for similar cores:
	printf '%s' "`sha1sum <"$d/vmcore" | cut -d" " -f1`" >"$d/uuid"

	# Copy/move vmcore directory to abrt spool dir.
	# We use .new suffix - we must make sure abrtd doesn't try
	# to process partially-copied directory.
	#
	# This is the efficient way:
	#mv -- "$d" "$dst.new" || continue
	# ...and this is what selinux forces me to do
	# (otherwise files have wrong context and abrtd can't access them):
	cp -r --no-preserve=all -- "$d" "$dst.new" || {
		rm -rf -- "$dst.new"
		continue
	}
	$move_core && rm -rf -- "$d"

	chown -R 0:0 -- "$dst.new"
	chmod -R u+rwX,go-rwxst -- "$dst.new"
	mv -- "$dst.new" "$dst"
done
