#!/bin/bash

TIMESTAMP=`date +"%Y-%m-%d %H_%M_%S"`
SIDR_PATH="/Applications/SoundID Reference.app"
DRIVER_PATH="/Library/Audio/Plug-Ins/HAL/SoundID Reference.driver"

# Check if daemon flag was passed
# Daemon mode:
# * No output or prompts
# * Does not restart CoreAudio or SIDR
# * Run infinitely until Ctr+C or kill is called
for i in "$@"
do
case $i in
    --daemon)
        DAEMON=1
        shift
    ;;
    *)
    ;;
esac
done

if [ -z ${DAEMON+x} ];
then
    # Display disclaimer
    echo "This script creates essential log files to troubleshoot SoundID Reference audio driver issues. "
    echo "You will be asked for your password in the process to perform some administrative tasks. "
    echo "Note that the SoundID Reference application and CoreAudio will be restarted in the process. "
    echo ""

    # Wait for user to start
    read -n 1 -s -r -p "Press any key to continue"
    echo ""
    echo ""

    # Redirect all stderr generated by this script to /dev/null
    exec 2> /dev/null

    # Check if SIDR is running
    SIDR_PID=`ps ax | grep "${SIDR_PATH}/Contents/MacOS/SoundID Reference" | grep -v grep | awk '{print $1}'`
    if [[ ! -z "$SIDR_PID" ]]
    then
        echo "* Quitting SoundID Reference"
        kill -s HUP $SIDR_PID
    else
        echo "* SoundID Reference is not running"
    fi
fi

# Start logging HAL
HAL_LOG_FILE="${HOME}/Library/Application Support/Sonarworks/Logs/HAL ${TIMESTAMP}.log.gz"
log stream --predicate '(process CONTAINS "Core-Audio") || (process == "coreaudiod")' --level debug | gzip -9 -c > "${HAL_LOG_FILE}" &
LOG_PID=$!

# Always do a clean exit
function handle_kill()
{
    # Stop logger
    kill -s HUP $LOG_PID
    sleep 1
    exit
}
trap handle_kill SIGHUP
trap handle_kill SIGINT
trap handle_kill SIGKILL
trap handle_kill SIGTERM
trap handle_kill SIGQUIT

if [ -z ${DAEMON+x} ];
then
    # Restart CoreAudio (restarts SoundID driver)
    echo "* Restarting CoreAudio and reloading SoundID driver"
    sudo launchctl kickstart -kp system/com.apple.audio.coreaudiod

    # Start SoundID Reference app
    echo "* Launching SoundID Reference"
    open "${SIDR_PATH}"

    # Wait for user to stop logging
    echo ""
    echo "Press any key to stop logging" # We need this because next command sometimes freezes without output
    read -n 1 -s -r -p ""
    echo ""
    echo "* Stopping logging"
    kill -s HUP $LOG_PID
    sleep 1
    echo "* The HAL log is written in ${HAL_LOG_FILE}"
fi

# Dump macOS, hardware and driver info into separate log file
if [ -z ${DAEMON+x} ];
then
    echo "* Gathering driver and system information"
fi
SETUP_LOG_FILE="${HOME}/Library/Application Support/Sonarworks/Logs/Setup ${TIMESTAMP}.log"

SIDR_VERSION=`defaults read "${SIDR_PATH}/Contents/Info.plist" CFBundleVersion`
echo "SoundID Reference version: ${SIDR_VERSION}" >> "${SETUP_LOG_FILE}"
SIDR_HASH=`md5 -r "${SIDR_PATH}/Contents/MacOS/SoundID Reference" | awk '{print $1}'`
echo "SoundID Reference hash: ${SIDR_HASH}" >> "${SETUP_LOG_FILE}"

DRIVER_VERSION=`defaults read "${DRIVER_PATH}/Contents/Info.plist" CFBundleVersion`
echo "Driver version: ${DRIVER_VERSION}" >> "${SETUP_LOG_FILE}"
DRIVER_HASH=`md5 -r "${DRIVER_PATH}/Contents/MacOS/SoundID Reference" | awk '{print $1}'`
echo "Driver hash: ${DRIVER_HASH}" >> "${SETUP_LOG_FILE}"

uname -a >> "${SETUP_LOG_FILE}"
sw_vers >> "${SETUP_LOG_FILE}"
system_profiler -detailLevel mini >> "${SETUP_LOG_FILE}"
if [ -z ${DAEMON+x} ];
then
    echo "* The driver and system information is written in ${SETUP_LOG_FILE}"
fi

if [ -z ${DAEMON+x} ];
then
    # Open log directory
    open "${HOME}/Library/Application Support/Sonarworks/Logs/"
fi

if [ -n "${DAEMON}" ];
then
    # Infinite loop to keep on running
    while :; do
    sleep 60
    done
fi
