#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
APP_PARENT="$(cd "$SCRIPT_DIR/../../.." && pwd)"

if [[ -z "${FILEPULSE_LAUNCH_CWD:-}" ]]; then
  export FILEPULSE_LAUNCH_CWD="$APP_PARENT"
fi

WORK_DIR="$APP_PARENT"
if [[ ! -w "$WORK_DIR" ]]; then
  WORK_DIR="${HOME}/Library/Application Support/FilePulse"
  mkdir -p "$WORK_DIR"
fi

cd "$WORK_DIR"
# Running the agent with LaunchServices/XPC context caused repeated
# AppKit status-item scene activation failures on some macOS setups.
# Detach from that context before starting the real binary.
unset XPC_SERVICE_NAME
unset __CFBundleIdentifier
nohup "$SCRIPT_DIR/FilePulse.bin" --mode agent "$@" >/dev/null 2>&1 &
exit 0
