#!/bin/sh
#
# Start gdb for kdump crash analysis
#
# Usage: gdb-kdump [-v vmlinux] [vmcore [gdb options...]]
#
# The script starts gdb using the currently running kernel image
# and the appopriate crash dump file.  If the kernel image is
# compressed, it's decompressed automatically.
# 
# When no arugment is given, the latest crash dump file is probed.
#
# The script also passes the gdb macros useful for analysis of crash
# dump.

. /etc/sysconfig/kdump

bootdir="/boot"

if [ "$1" = "-v" ]; then
    vmlinux="$2"
    if [ ! -f "$vmlinux" ]; then
	echo "Cannot find vmlinux file $vmlinux, aborting"
	exit 1
    fi
    shift 2
else
    vmlinux="$bootdir"/vmlinux-`uname -r`
    if [ ! -f $vmlinux ]; then
	if [ -f "$bootdir/vmlinux" ]; then
	    vmlinux="$bootdir/vmlinux"
	elif [ -f $vmlinux.gz ]; then
	    if gunzip $vmlinux.gz; then
		echo "Uncompressed $vmlinux.gz"
	    else
		echo "Cannot uncompress $vmlinux.gz, aborting"
		exit 1
	    fi
	else
	    echo "No useful vmlinux is found in $bootdir"
	    exit 1
	fi
    fi
fi
echo "Using $vmlinux as vmlinux"

if [ -n "$1" ]; then
    if [ -f "$1" ]; then
	dumpfile="$1"
	shift
    else
	echo "Dumpfile $1 cannot be found"
	exit 1
    fi
else
    dumpfile=`ls $KDUMP_SAVEDIR/*-*-*-*:*/vmcore 2>/dev/null | sort -r | head -n 1`
    if [ -n "$dumpfile" -a -f "$dumpfile" ]; then
	echo "Using $dumpfile as dumpfile"
    else
	echo "Cannot find the latest dumpfile"
	exit 1
    fi
fi

exec /usr/bin/gdb --command=/usr/share/gdbinit.kdump $vmlinux $dumpfile $*
