#!/bin/bash

readconfigvar() {
    fname=$1
    if [ ! -r "$fname" ]; then
        return
    fi
    bname="[$2]"
    vname=$3
    value=
    cat "$fname" | sed -e 's/\r$//' -e 's/^\r//' | grep -e '^\[' -e "^${vname}=" | {
        while true; do
            read line
            if [ ! $? = 0 ] ; then
                return
            fi
            if [ "$line" = "$bname" ] ; then
                while true ; do
                    read line
                    if [ ! $? = 0 ] ; then
                        return
                    fi
                    lstart=`echo "$line" | head -c 1`
                    if [ "$lstart" = '[' ] ; then
                        return
                    fi
                    vlname=`echo "$line" | sed 's/=.*//;t;s/.*//'`
                    if [ "$vlname" = "$vname" ] ; then
                        val=`echo "$line" | sed 's/[^=]*=//'`
                        eval "echo $val"
                        return
                    fi
                done
            fi
        done
    }
}


# ARC_LOCATION
ARC_LOCATION=${ARC_LOCATION:-/usr}


if [ "x$ARC_CONFIG" = "x" ]; then
    if [ -r $ARC_LOCATION/etc/arc.conf ]; then
        ARC_CONFIG=$ARC_LOCATION/etc/arc.conf
    elif [ -r /etc/arc.conf ]; then
        ARC_CONFIG=/etc/arc.conf
    fi
fi
if [ "x$ARC_CONFIG" = "x" ]; then
    echo "Can't find configuration file."
    exit 1
fi
if [ ! -f "${ARC_CONFIG}" ]; then
    echo "Can't find configuration file at ${ARC_CONFIG}."
    exit 1
fi

ARCHED="${ARC_LOCATION}/sbin/arched"
if [ ! -f "${ARCHED}" ]; then
    echo "Can't find arched at ${ARCHED}."
    exit 1
fi

LOGFILE=`readconfigvar "$ARC_CONFIG" arex logfile`
LOGFILE=${LOGFILE:-/var/log/arc/arex.log}
COREDIR=`dirname "${LOGFILE}"`/arccore
if [ ! -d "${COREDIR}" ]; then
    echo "Can't find core collection folder at ${COREDIR}."
    exit 1
fi
backtrace_generated=no
for corename in "${COREDIR}"/*; do
    echo "${corename}" | grep '\.backtrace$'
    if [ ! "$?" = '0' ]; then
        backtracename="${corename}.backtrace"
        echo "--- Processing ${corename} - storing into ${backtracename} ---"
        gdb --batch --core="${corename}" "${ARCHED}" --eval-command='thread apply all bt full' 1>"${backtracename}" 2>&1
        backtrace_generated=yes
    fi
done

if [ $backtrace_generated = yes ]; then
  echo "Please send generated backtrace(s) to support@nordugrid.org or report them on http://bugzilla.nordugrid.org"
fi
