#!/bin/bash

set -u

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
INSTALL_HELPER="$SCRIPT_DIR/install-timelapse.sh"
TL_LOG="/tmp/agentshore-timelapse-install.log"

CONSOLE_USER="$(stat -f '%Su' /dev/console 2>/dev/null || true)"
if [[ -z "${CONSOLE_USER}" || "${CONSOLE_USER}" == "root" ]]; then
  exit 0
fi
CONSOLE_UID="$(id -u "${CONSOLE_USER}" 2>/dev/null || true)"
if [[ -z "${CONSOLE_UID}" ]]; then
  exit 0
fi

if [[ ! -x "$INSTALL_HELPER" ]]; then
  exit 0
fi

if ! launchctl asuser "${CONSOLE_UID}" /usr/bin/sudo -H -u "${CONSOLE_USER}" \
     /bin/bash "$INSTALL_HELPER" >"$TL_LOG" 2>&1; then
  DIALOG_BODY="The optional timelapse-capture toolchain did not finish installing. The desktop app still works; you can retry from the Start screen.\\n\\nDetails: $TL_LOG"
  launchctl asuser "${CONSOLE_UID}" /usr/bin/sudo -H -u "${CONSOLE_USER}" \
    /usr/bin/osascript -e "display alert \"AgentShore timelapse install failed\" message \"$DIALOG_BODY\" buttons {\"OK\"}" \
    >/dev/null 2>&1 || true
fi

exit 0
