#!/bin/bash
#
# Open $EDITOR (some vim variant) at the currently open line in Xcode
#

# TODO: There are a few issues with this script:
# - I cannot find a way to get the _actual_ focused window in Xcode, just all
#   documents that are open in general, which is why it fuzzy finds.
# - I didn't find a way to print to stdout from the script so I have to capture
#   everything and filter on lines with the special PATH: prefix
#
# shellcheck disable=SC2312,SC3045

set -eu

read -r -d '' script <<EOF || true
var processes = Application("System Events").processes
var nameGetter = ObjectSpecifier().name
var apps = processes.whose({_match: [nameGetter, "Xcode"]})
for (const appIndex in apps) {
  var xcode = Application(apps[appIndex].file().posixPath.get())
  var activeWorkspace = xcode.activeWorkspaceDocument()
  if (activeWorkspace !== null) {
    console.log("WORKSPACE:" + activeWorkspace.path.get())
    var documents = xcode.sourceDocuments()
    for (const documentIndex in documents) {
      var document = documents[documentIndex];
      console.log("PATH:" + document.path() + ":" + document.selectedCharacterRange.get());
    }
  }
}
EOF

all_output=$(mktemp)
if ! echo "${script}" | osascript -l JavaScript > "${all_output}" 2>&1; then
  echo "error: failed to fetch files: $(grep -v PATH: "${all_output}")" >&2
  exit 1
fi

paths=$(grep PATH: "${all_output}" || true)
if [ -z "${paths}" ]; then
  echo "error: no open files in Xcode" >&2
  exit 1
fi

current_workspace=""
while read -r workspace; do
  if [ "${workspace}" = "$(pwd)" ]; then
    current_workspace="${workspace}"
    break
  fi
done << EOF
"$(grep WORKSPACE: "${all_output}" | cut -d: -f2 | xargs dirname || true)"
EOF

if [ -n "${current_workspace}" ]; then
  paths=$(grep "PATH:${current_workspace}/" "${all_output}" | sed "s=${current_workspace}/==g" || true)
fi

if [ -z "${paths}" ]; then
  echo "error: no open files in '${current_workspace}'" >&2
  exit 1
fi

selected=$(echo "${paths}" | cut -d: -f2 | fzf)

start_position=$(echo "${paths}" | grep "^PATH:${selected}:" | cut -d: -f3 | cut -d, -f1)

exec "${EDITOR:-}" "${selected}" "+call cursor(byte2line(${start_position}), ${start_position} - line2byte(byte2line(${start_position})))"
