#!/usr/bin/env bash
#
# Get a Sleep profile and save it into /ifs/profiles

usage()
{
    cat <<EOF
Usage:
         isi_get_sleep [ -r | -s ] [ -t seconds ] [ -d /dir ] [ name ]

default:  
         isi_get_sleep  : profile for 20 seconds, save to /ifs/profiles

options:
         isi_get_sleep -r                 : start sleep profiling
         isi_get_sleep -s -d /var/crash   : stop and save to /var/crash

EOF
}

# defaults: RUN and SAVE, run for 20 seconds, save to /ifs/profiles
RUN=1
SAVE=1
TIME=20
DEST=/ifs/profiles

while getopts t:d:hrs opt; do
   if [ $opt = "t" ]; then TIME=$OPTARG; fi 
   if [ $opt = "d" ]; then DEST=$OPTARG; fi 
   if [ $opt = "r" ]; then SAVE=0; fi
   if [ $opt = "s" ]; then RUN=0;  fi
   if [ $opt = "h" ]; then usage;  exit; fi
done

if [ $RUN -eq 1 ]; then
   echo -n "Starting profile... "

   sysctl -aN | \
    egrep "kern.isi_profile_level|debug.profile.*.clear" | \
    xargs -n1 -I%% sysctl %%=1 &>/dev/null
fi

if [ $SAVE -eq 0 ]; then
   echo -e "\nrun isi_get_sleep -s to stop and save"
   exit 0;
fi

[ $RUN -eq 1 ] && sleep $TIME

if sysctl -n kern.isi_profile_level | grep -q 1; then
   echo -n "stopping ..."
else
   echo -n "profiling was not enabled .. profile may be empty .. "
fi

sysctl kern.isi_profile_level=0 > /dev/null

PROFNAME=$BASH_ARGV
if [ "$PROFNAME" = "" ] ; then
   PROFNAME=unnamed
fi

FILENAME=${PROFNAME}_`hostname`_`date +"%b_%d_%H_%M_%S"`.slp
CFILENAME=${FILENAME}.gz

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

echo -n " saving..."
sysctl debug.profile | gzip -c > $DEST/$CFILENAME

echo "done.  filename is $DEST/$CFILENAME"

exit
