#!/bin/bash

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
LOG_AGENT_FILENAME="com.sonarworks.soundid.reference.systemwide.hallogger.plist"
LOG_AGENT_PATH="${HOME}/Library/LaunchAgents/${LOG_AGENT_FILENAME}"
TEMPLATE_PATH="${SCRIPT_DIR}/HALLoggerDaemon.app/Contents/Resources/${LOG_AGENT_FILENAME}"

# Display disclaimer
echo "This process will install a HAL logger as a background service on your system."
echo "Please be aware that you will be asked for your password during the installation."
echo "Furthermore, the logger will run continuously and collect logs until turned off."
echo "To turn it off and stop gathering logs, run the uninstaller."
echo ""

# Wait for user to start
read -n 1 -s -r -p "Press any key to begin installation or close this window to cancel."
echo ""
echo ""

if [ -f "${LOG_AGENT_PATH}" ];
then
    echo " * Removing previous installation if any"
    launchctl unload "${LOG_AGENT_PATH}"
    rm "${LOG_AGENT_PATH}"
fi

echo " * Writing new launch agent file"
TEMPLATE_CONTENTS=$(sed 's/"/\\"/g' "${TEMPLATE_PATH}")
PATH_TO_HAL_LOGGING_DAEMON="${SCRIPT_DIR}/HALLoggerDaemon.app/Contents/MacOS/HALLoggerDaemon" eval "echo \"${TEMPLATE_CONTENTS}\"" > "${LOG_AGENT_PATH}"

echo " * Launching the logger daemon"
launchctl load "${LOG_AGENT_PATH}"

echo " * Done"
