#!/bin/sh
set -eu

# Build a PATH directory of symlinks to the host-command bridge, one per command
# the host actually has. Generated at launch (not at build time) because which
# tools a developer has installed is a property of their machine, and printed on
# stdout for the wrapper to append to PATH.

bridge="/app/lib/cursor/cursor-host-shim"
runtime_dir="${XDG_RUNTIME_DIR:-/tmp}"
host_bin="$runtime_dir/cursor-host-bin"
tmp_dir="$runtime_dir/cursor-host-bin.$$"

list_commands='
path_value="$1"
IFS=:
for dir in $path_value; do
  [ -d "$dir" ] || continue
  find "$dir" -maxdepth 1 \( -type f -o -type l \) -perm /111 -printf "%f\n" 2>/dev/null || true
done
'

host_script='
PATH="${PATH:-}:/usr/local/bin:/usr/bin:/bin:/snap/bin:$HOME/.local/bin:$HOME/bin"
export PATH

sh -c "$1" cursor-host-path "$PATH" || true

case "${SHELL:-}" in
  */bash|*/zsh|*/ksh)
    shell_path="$("$SHELL" -ic '"'"'printf "%s\n" "$PATH"'"'"' 2>/dev/null | sed -n "/\//h; \${g;p;}" || true)"
    if [ -n "$shell_path" ]; then
      sh -c "$1" cursor-host-shell-path "$shell_path" || true
    fi
    ;;
esac
'

rm -rf "$tmp_dir"
mkdir -p "$tmp_dir"

flatpak-spawn --host sh -c "$host_script" cursor-host-list "$list_commands" 2>/dev/null \
  | sort -u \
  | while IFS= read -r name; do
      case "$name" in
        ""|.|..|*/*|*' '*|*'	'*|*:*|*';'*|*"'"*|*'"'*|*'\'*|*'`'*|*'$'*|*'('*|*')'*|*'{'*|*'}'*|*'['*|*']'*|*'<'*|*'>'*|*'|'*|*'&'*)
          continue
          ;;
        sh|bash|dash|zsh|env|ls|cat|cp|mv|rm|sed|awk|grep|find)
          # Keep the sandbox's own shell and coreutils authoritative: shelling
          # those out to the host would make file operations disagree with what
          # the editor itself reads and writes, and the integrated terminal has
          # to keep running inside the sandbox for the editor to drive it.
          continue
          ;;
      esac
      ln -s "$bridge" "$tmp_dir/$name" 2>/dev/null || true
    done

rm -rf "$host_bin.old"
if [ -d "$host_bin" ]; then
  mv "$host_bin" "$host_bin.old" 2>/dev/null || rm -rf "$host_bin"
fi
mv "$tmp_dir" "$host_bin"
rm -rf "$host_bin.old"

printf '%s\n' "$host_bin"
