#!/bin/bash

set -eu

current_path="$(xcode-select --print-path)"
apps="$(find /Applications -maxdepth 1 -name "Xcode*.app")"
other_apps=""

for app in ${apps}; do
  other_apps="${other_apps}${app}"
done

case "${#other_apps[@]}" in
  0)
    echo "No other Xcode found to switch to"
    exit 1
    ;;
  1)
    eval "sudo /usr/bin/xcode-select --switch ${other_apps}"
    ;;
  *)
    printf '%s\n' "${other_apps}" \
      | fzf --query="${1:-}" \
      | xargs -I{} sudo xcode-select --switch "{}"
    ;;
esac

echo "Previous Xcode was   '${current_path}'"
echo "Current Xcode is now '$(xcode-select --print-path)'"
if [ -n "${DEVELOPER_DIR:-}" ]; then
  echo "\$DEVELOPER_DIR is '${DEVELOPER_DIR:-}'"
  # shellcheck disable=SC2312
  echo "Current Xcode without \$DEVELOPER_DIR is '$(env -i -- /usr/bin/xcode-select --print-path)'"
fi
