#!/bin/sh

ITRACE_RUNNING="kern.itrace.running"
BUFFER_RUNNING="debug.ktr.running"
BASEDIR="/ifs"
SET_ITRACE=0
WAIT=0

usage()
{
    cat << _USAGE_
usage: isi_save_itrace [-sw] [-d directory] [itrace_name]
    -d      Directory to save itrace in; /itraces/ will be added to the path.
                Default: $BASEDIR
    -s      Set the itrace sysctl $ITRACE_RUNNING to 1.
    -w      Wait for the itrace sysctl to change from on to off before saving.
                The default behavior is to save if the sysctl is off for any
                reason.
_USAGE_
    exit 1
}

args=`/usr/bin/getopt hd:sw $*`

if [ $? -ne 0 ]; then
    usage
fi

set -- $args
for i; do
    case "$i"
    in
        -h)
            usage;
            break;;
        -d)
            BASEDIR="$2";
            shift; shift;;
        -s)
            SET_ITRACE=1;
            shift;;
        -w)
            WAIT=1;
            shift;;
        --)
            shift;
            break;;
    esac
done

TRACENAME=$1
if [ "$TRACENAME" = "" ] ; then
        TRACENAME=unnamed
fi

if [ $SET_ITRACE -eq 1 ]; then
    echo "Starting itrace... "
    /sbin/sysctl $BUFFER_RUNNING=1
    /sbin/sysctl $ITRACE_RUNNING=1
elif [ $WAIT -eq 1 ]; then
    echo -n "Waiting for trace to start... "
    while [ `/sbin/sysctl -n $BUFFER_RUNNING` -eq 0 ] ; do sleep 1; done
fi

echo -n "Waiting for trace to end..."
# Check that the itrace is still running every now and then
while [ `/sbin/sysctl -n $BUFFER_RUNNING` -eq 1 ] ; do sleep 5; done

# Form filename timestamped with when the trace was saved
FILENAME=${TRACENAME}_`hostname`_`date +"%b_%d_%H_%M_%S"`.itr
CFILENAME=${FILENAME}.gz

if [ ! -d "$BASEDIR/itraces" ]; then
    echo -n " making $BASEDIR/itraces..."
    mkdir -p "$BASEDIR/itraces"
fi

echo -n " saving..."
ktrdump -ctH | gzip -c > "$BASEDIR/itraces/$CFILENAME"

echo " done.. filename is $BASEDIR/itraces/$CFILENAME"
