#!/bin/sh

# Validate arguments
if [ "$#" -lt 1 ]; then
  echo "Usage: $0 DIRECTORY [VARNAME_1 .. VARNAME_N]" >&2
  /fs/etfs/config/current/CustomerExtensions/SendEvent "Snapshot.CaptureError"
  exit 1
fi
if ! [ -e "$1" ]; then
  echo "$1 not found" >&2
  /fs/etfs/config/current/CustomerExtensions/SendEvent "Snapshot.CaptureError"
  exit 1
fi
if ! [ -d "$1" ]; then
  echo "$1 not a directory" >&2
  /fs/etfs/config/current/CustomerExtensions/SendEvent "Snapshot.CaptureError"
  exit 1
fi

# Create a unique directory
i=0
basename=snapshot
basedir=$1/
while [[ -d $basedir$basename$i ]] ; do
    let i++
done
echo "Creating directory \"$basename$i\"..."
mkdir $basedir$basename$i/

#this function does not run on PV version lower than 6.x so is commented out
# Capture screenshot
#echo "Capturing screenshot..."
#/fs/etfs/config/current/CustomerExtensions/GetScreenshot $basedir$basename$i/screen.png

# Capture variable values
echo "Capturing variable values..."
shift # Shift arguments to the left by 1
for varname in "$@" ; do
    echo "Capturing \"$varname\""
    touch $basedir$basename$i/variables.txt
    /fs/etfs/config/current/CustomerExtensions/GetVariable "$varname" >> $basedir$basename$i/variables.txt
done

# Copy saved strings file
echo "Copying suvstore* files..."
cp -c /fs/etfs/nvdata/suStrings* $basedir$basename$i

# Capture .core files, sloginfo, pidin, and CPU info
echo "Copying core dump files..."
cp -c /fs/etfs/config/current/*.core $basedir$basename$i
rm -rf /fs/etfs/config/current/*.core

echo "Saving pidin to file..."
pidin -fabNpJBA > $basedir$basename$i/pidin.txt
echo "Saving CPU info..."
pidin times > $basedir$basename$i/pidin_times.txt
pidin ttimes > $basedir$basename$i/pidin_thread_times.txt
hogs -i1 > $basedir$basename$i/hogs.txt
echo "Saving sloginfo to file - runs continually..."
sloginfo > $basedir$basename$i/sloginfo.txt

# Sync and indicate done with a file and a PV event (if it exists) - this wont run if sloginfo is set to -w since that process never finishes
sync
touch $basedir$basename$i/done
/fs/etfs/config/current/CustomerExtensions/SendEvent "Snapshot.CaptureSuccess"
echo "Snapshot complete at $basedir$basename$i/"
