#!/bin/bash
# ZR R3D Listener
#
# Wakes ZR RAW Extended when one of its selected directories is available.
# The app performs the privacy-sensitive media scan and stability check itself.
# This helper never reads RAW files, modifies source media, or contacts a network.

set -u

APP="${ZR_LISTENER_APP:-/Applications/ZR RAW Extended.app}"
SUPPORT="${ZR_LISTENER_SUPPORT:-$HOME/Library/Application Support/ZR RAW Extended}"
LOG_DIR="${ZR_LISTENER_LOG_DIR:-$HOME/Library/Logs/ZR RAW Extended}"
DIRECTORIES="$SUPPORT/listener_directories.txt"
ENABLED="$SUPPORT/listener_enabled"
TRIGGER="$SUPPORT/pending_directories.txt"
mkdir -p "$SUPPORT" "$LOG_DIR"
[[ -d "$APP" ]] || exit 0
[[ "$(cat "$ENABLED" 2>/dev/null || true)" == "1" ]] || exit 0
[[ -s "$DIRECTORIES" ]] || exit 0

mounted_root=""
while IFS= read -r root || [[ -n "$root" ]]; do
    if [[ -d "$root" ]]; then
        mounted_root=1
        break
    fi
done < "$DIRECTORIES"

if [[ -n "$mounted_root" ]]; then
    temporary="$TRIGGER.$$"
    date +%s > "$temporary"
    mv -f "$temporary" "$TRIGGER"
    if [[ "${ZR_LISTENER_DRY_RUN:-0}" != "1" ]]; then
        open -gj -a "$APP"
    fi
fi
