#!/bin/sh
#
# Script that collects relevant files after a hostd crash:
#    -- Log files
#    -- Trace buffer
#    -- Configuration files
#    -- Runtime files (vMotion journals, stats, etc.)
#    -- Core file (if present)
#

TMPDIR=/tmp
PIDFILE=/var/run/vmware/vmware-hostd.PID
STAGEDIR_PFX=hostd-support
TARBALL_PFX=/var/log/vmware/hostd-support

#
# Verify that script is running as root
#

if [ `id -u` != "0" ] ; then
    echo "Only root can run this script"
    exit 1
fi

#
# Gracefully clean up on signals
#

function cleanup {
    echo "Caught signal: cleaning up..."
    cd $TMPDIR
    rm -rf $STAGEDIR
    if [ "$TARBALL" != "" ] ; then
        rm -f $TARBALL
    fi
    exit 1
}

trap cleanup 1 2 3 6 7 8 10 11 13 14 15 16 24 25 26 27 30 31      

#
# If there's no PID file, assume clean shutdown and don't harvest anything
#

PID=`cat $PIDFILE 2> /dev/null`
if [ "$PID" == "" ] ; then
    exit 0
fi
STAGEDIR=$STAGEDIR_PFX-$PID

#
# Create symlinks in staging directory, then use tar's h option to dereference
#

cd $TMPDIR
mkdir -p $STAGEDIR
if [ $? != 0 ] ; then
    logger -p daemon.err -t "hostd-support" "Failed to create directory $STAGEDIR"
    exit 1
fi

# Logs
mkdir -p $STAGEDIR/logs
for x in /var/log/vmware/hostd-*.log ; do
    if [ "$x" == "/var/log/vmware/hostd-trace.log" ] ; then
        # Always grab the trace log
        ln -s $x $STAGEDIR/logs
    else
        # Exclude any logs that don't correspond to this PID
        if head -1 $x | grep -q "Log for VMware ESX Server" ; then
            # Beginning of the log: check for PID match
            if head -1 $x | grep -q "pid=$PID" ; then
                ln -s $x $STAGEDIR/logs
            fi
        else
            # Rotated log: can't tell if it's for this PID, so grab just in case
            ln -s $x $STAGEDIR/logs
        fi
    fi
done

# Configuration files
mkdir -p $STAGEDIR/config
ln -s /etc/vmware/hostd $STAGEDIR/config

# Runtime files
mkdir -p $STAGEDIR/runtime
ln -s /var/lib/vmware/hostd/journal $STAGEDIR/runtime
ln -s /var/lib/vmware/hostd/stats $STAGEDIR/runtime

# Core file (if created)
if [ -f /var/core/$PID.core ]; then
    mkdir -p $STAGEDIR/core
    ln -s /var/core/$PID.core $STAGEDIR/core
fi

#
# Rotate old support tarballs, keeping a maximum of 4
#

if [ -f $TARBALL_PFX-3.tgz ] ; then
    rm -f $TARBALL_PFX-3.tgz
fi
if [ -f $TARBALL_PFX-2.tgz ] ; then
    mv -f $TARBALL_PFX-2.tgz $TARBALL_PFX-3.tgz
fi
if [ -f $TARBALL_PFX-1.tgz ] ; then
    mv -f $TARBALL_PFX-1.tgz $TARBALL_PFX-2.tgz
fi
if [ -f $TARBALL_PFX.tgz ] ; then
    mv -f $TARBALL_PFX.tgz $TARBALL_PFX-1.tgz
fi

#
# Generate the new support tarball
#

TARBALL=$TARBALL_PFX.tgz
tar zchf $TARBALL $STAGEDIR

#
# Get rid of the staging directory
#

rm -rf $STAGEDIR
exit 0
