#!/bin/bash

# Finds all available Xcodes on system and sets appropriate one as default
# Will choose the latest Xcode available, excluding beta versions

# Find all available Xcodes
echo "Scanning for available Xcode installations..."
XCODES=`mdfind "kMDItemCFBundleIdentifier == 'com.apple.dt.Xcode' && kMDItemContentType == 'com.apple.application-bundle'"`

# Output the found Xcodes
i=1
for xcode in $XCODES; do
  echo "$i: $xcode"
  i=$((i+1))
done

# Pick the latest non-beta version
echo "Selecting latest non-beta version..."
for xcode in $XCODES; do
  if [[ $xcode != *"beta"* ]]; then
    XCODE_PATH=$xcode
  fi
done

sudo xcode-select -s "$XCODE_PATH/Contents/Developer"
echo "Set default Xcode to $XCODE_PATH"
xcodebuild -version
