#!/bin/bash
# @@@ START COPYRIGHT @@@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
# @@@ END COPYRIGHT @@@
#
# mondump <pid> to <core>
#
if [ $# -lt 2 ]; then
    echo "usage: $0 <pid> <core>"
    exit 1
fi

# change this to 1 for tracing to /tmp/mondump<pid>
trace=0

if [ $trace = 1 ]; then
    TMP=/tmp/mondump$$
    trap "rm -f ${TMP}; exit 1" 1 2 13 15
fi

#
# collect arguments
#
pid=$1
core=$2
tgtcore=$core
if [ $trace = 1 ]; then
    echo "input: pid=$pid" >> $TMP
    echo "input: core=$core" >> $TMP
fi

dir=`dirname $core`
core=`basename $core`

#
# create core-file
#
if [ $trace = 1 ]; then
    echo "" >> $TMP
    echo "create core-file" >> $TMP
    echo "cd $dir" >> $TMP
    echo "gdb" >> $TMP
    echo "  attach $pid" >> $TMP
    echo "  gcore $core" >> $TMP
    echo "  detach" >> $TMP
    echo "" >> $TMP
fi

cd $dir
gdb <<eof
attach $pid
gcore $core
detach
eof
ret=$?
if [ $trace = 1 ]; then
    echo "gdb exit $ret" >> $TMP
fi

if [ $ret = 0 ]; then
    # make sure file created
    if [ ! -e $dir/$core ]; then
        ret=1
        if [ $trace = 1 ]; then
            echo "$dir/$core were not created" >> $TMP
        fi
    fi
fi

if [ $trace = 1 ]; then
    echo "exit $ret" >> $TMP
fi
exit $ret
