#!/bin/zsh

# Copyright C 2010-2010 by Isilon Systems, Inc. All rights not expressly
# granted herein are reserved.
# Created in the United States of America.
#
# This digital media is protected by U.S. and international copyright and
# intellectual property laws. Unless otherwise specified, all information
# and screens appearing as part of this digital medium, including
# software, services, documents, text, images, icons, and logos design;
# the selection, assembly, arrangement, and design thereof; and the code
# that enables its presentation, are the sole property of Isilon Systems,
# Inc.
#
# Except as otherwise required by applicable law, no part of any
# copyrighted material may be reproduced, modified, translated,
# distributed, published, or transmitted by any means, electronic or
# mechanical, for any purpose, without the prior written consent of Isilon
# Systems.
#
# Isilon and Isilon Systems are registered trademarks of Isilon Systems,
# Inc.  Legion is a trademark of Isilon Systems, Inc.  All other
# trademarks and registered trademarks are the property of their
# respective holders.

#####################################################################
# USAGE: This script allows one to load gdb with appropriate context
# for core files. This includes uncompressing the core if necessary,
# setting search paths and absolute-prefix for symbol directories,
# etc.
#####################################################################

CMDFILE=/tmp/gdbcoreinit
IFSCORE=/ifs/.ifsvar/tmp/core

if [ $# -lt 2 ]; then
    echo "Usage: $0 <executable> <core file> [symbol directory]"
    exit 1
fi

EXEC=$1
CORE=$2

echo "Executable: ${EXEC}"
echo "Core: ${CORE}"

if [ ! -e ${CORE} ]; then
    echo "Core file '${CORE}' not found, exiting."
    exit 1
fi

# Test the extension
if [ "${CORE##*.}" = "gz" ]; then
    if ! mount | grep -q OneFS; then
	echo "/ifs not mounted, needed to uncompress core"
	exit 1
    fi
    CORETIME=$(stat -r ${CORE} | cut -f 11 -d\ )
    NEWCORE=${IFSCORE}/$(basename ${CORE} .core.gz).$(hostname).${CORETIME}.core
    if [ ! -e ${NEWCORE} ]; then
	mkdir -p ${IFSCORE} || exit 1
	gzip -d < ${CORE} > ${NEWCORE} || exit 1
    fi
    echo "Uncompressed core: ${NEWCORE}"
    CORE=${NEWCORE}
fi

rm ${CMDFILE}

# Load gdbinit if present
if [ -e ~/.gdbinit ]; then
    echo "source ~/.gdbinit" >> ${CMDFILE}
fi

if [ $# -ge 3 ]; then
    SYM=$3
    echo "Symbol directory: ${SYM}"
    EXEC=${SYM}/${EXEC}
    echo "set solib-absolute-prefix ${SYM}" >> ${CMDFILE}
    echo "set solib-search-path ${SYM}/usr/lib ${SYM}/usr/likewise/lib" >> ${CMDFILE}
fi

echo "file ${EXEC}" >> ${CMDFILE}
echo "core ${CORE}" >> ${CMDFILE}

echo "Loading gdb with these commands:"
echo "--------------------------------"
cat ${CMDFILE}
echo "--------------------------------"

gdb -n -x ${CMDFILE}
