#!/bin/zsh

TEMP="inceptiondiagnose"

if [[ $UID != 0 ]]; then
    echo "Please run this script with sudo:"
    echo "sudo $0"
    exit 1
fi

SYSDIAGNOSE=false
if [ "$1" = "-sysdiagnose" ]; then
    SYSDIAGNOSE=true
fi

echo "This tool generates files that allow Stairwell to investigate issues with Inception Forwarder."
read "REPLY?Would you like to continue? Y/N?"
if [[ "$REPLY" =~ ^[Yy]$ ]]; then
    echo "Gathering debug logs..."
else
	echo "Exiting..."
    exit 0
fi

# Create temp dir
/bin/mkdir -p $TEMP

echo "getting forwarder status..."
# Dump current status of the forwarder
/Applications/Inception\ Forwarder.app/Contents/MacOS/Inception\ Forwarder status --json > $TEMP/status.json

echo "getting extension status..."
# Dump a copy of the SystemExtensionsDB plist
/usr/bin/defaults read /Library/SystemExtensions/db.plist > $TEMP/SystemExtensionsDB.txt

if [ $SYSDIAGNOSE = true ]; then
    echo "running sysdiagnose..."
    # In the future, gather process specific information by using the process parameter
    /usr/bin/sysdiagnose -b -f $TEMP
fi

echo "gathering logs..."
START_DATE=$(date -j -v-7d +"%Y-%m-%d")
/usr/bin/log show --source --start $START_DATE --style syslog --predicate 'subsystem == "com.stairwell.Inception.ProcessMonitor"' --info --debug > $TEMP/InceptionForwarder.log
/usr/bin/log show --source --start $START_DATE --style syslog --predicate 'subsystem == "com.stairwell.Inception.totem"' --info --debug > $TEMP/Totem.log

echo "sampling forwarder..."
# Sample the process
PID=$(/usr/bin/pgrep -u root com.stairwell.Inception.ProcessMonitor)
/usr/bin/sample $PID 30 -file $TEMP/sample.txt

echo "zipping results..."
# Zip it all up
/usr/bin/zip -r inceptionDiagnose.zip $TEMP

# Cleanup temp dir
/bin/rm -rf $TEMP

/usr/bin/open .
