#!/bin/sh
#
# Copyright IBM Corp. 2021
#
# s390-tools is free software; you can redistribute it and/or modify
# it under the terms of the MIT license. See LICENSE for details.
#

OPTION=NGDUMP
PREREQ="udev"

prereqs()
{
	echo "${PREREQ}"
}

case "${1}" in
	prereqs)
		prereqs
		exit 0
		;;
esac

. /scripts/functions
. /conf/conf.d/ngdump

MNTDIR="/ngdump"
DUMP="dump.elf"
META="ngdump.meta"
VMCORE="/proc/vmcore"

is_dump_part_ok()
{
	findmnt "$MNTDIR" >/dev/null 2>&1 && [ -e "$MNTDIR/$META" ]
}

save_logs()
{
	is_dump_part_ok || return
	[ -e "$VMCORE" ] && makedumpfile -f --dump-dmesg "$VMCORE" "$MNTDIR/crash.log"
	dmesg >"$MNTDIR/boot.log"
}

#
# The following steps make the firmware IPL the production system again.
# Otherwise, the firmware will boot the dumper again.
#
reipl()
{
	dir=$(findmnt -n -o TARGET debugfs)
	if [ -z "$dir" ]; then
		dir=/sys/kernel/debug
		mount -t debugfs none "$dir"
	fi
	echo 1 > "$dir/zcore/reipl"
	sleep 5 # To give console enough time to display last messages
	halt
}

quit()
{
	log_end_msg
	sync
	umount "$MNTDIR"
	reipl
}

bail_out()
{
	log_failure_msg "$1"
	save_logs
	quit
}

save_meta()
{
	local hash=$(sha256sum "$MNTDIR/$DUMP" | cut -f1 -d ' ')

	cat >"$MNTDIR/$META" <<EOF
version=1
file=$DUMP
sha256sum=$hash
EOF
}

log_begin_msg "NGDump"

[ -e "$NGDUMP_DEVICE" ] ||
	{ bail_out "Dump partition device '$NGDUMP_DEVICE' not found"; }

mkdir "$MNTDIR" && mount -t ext4 "$NGDUMP_DEVICE" "$MNTDIR"

is_dump_part_ok || { bail_out "Dump partition not found"; }

#
# We must save the dump as ELF format, because
# kdump compressed format is not supported by zgetdump yet
#
logsave "$MNTDIR/makedumpfile.log" makedumpfile -f -E --message-level 7 -d 31 "$VMCORE" "$MNTDIR/$DUMP"

[ $? -eq 0 ] || { bail_out "makedumpfile failed"; }

#
# Create a file containing meta information for zgetdump
#
save_meta

quit
