#!/bin/zsh
set -eu

# An explicit override is useful for development builds and for users who keep
# apps somewhere unusual. Respect it before every automatic discovery method.
if [[ -n "${RECORDCUE_APP:-}" ]]; then
  if [[ -d "$RECORDCUE_APP" ]]; then
    executable="$RECORDCUE_APP/Contents/MacOS/RecordCue"
  else
    executable="$RECORDCUE_APP"
  fi
  if [[ -x "$executable" ]]; then
    exec "$executable" --agent-cli "$@"
  fi
  print -u2 "RECORDCUE_APP does not point to a runnable RecordCue app or executable."
  exit 127
fi

# A future standalone CLI, or a user-created shim, is already the shortest and
# most stable route when present. Walk every PATH entry so a symlink to this
# wrapper can be skipped without hiding a real standalone CLI later in PATH.
wrapper_path="${0:A}"
for command_directory in "${path[@]}"; do
  [[ -n "$command_directory" ]] || command_directory="."
  command_path="$command_directory/recordcue"
  if [[ -f "$command_path" \
      && -x "$command_path" \
      && "${command_path:A}" != "$wrapper_path" ]]; then
    exec "$command_path" "$@"
  fi
done

for executable in \
  "/Applications/RecordCue.app/Contents/MacOS/RecordCue" \
  "$HOME/Applications/RecordCue.app/Contents/MacOS/RecordCue"; do
  if [[ -x "$executable" ]]; then
    exec "$executable" --agent-cli "$@"
  fi
done

# Applications can be moved on macOS. Ask Launch Services for the release app
# by bundle identifier instead of making the user discover its path.
if app_path="$(/usr/bin/osascript \
    -e 'POSIX path of (path to application id "com.frontmind.recordcue")' \
    2>/dev/null)"; then
  app_path="${app_path%/}"
  executable="$app_path/Contents/MacOS/RecordCue"
  if [[ -x "$executable" ]]; then
    exec "$executable" --agent-cli "$@"
  fi
fi

print -u2 "RecordCue was not found. Install and open the Mac App Store app, or set RECORDCUE_APP to the app or executable path."
exit 127
