#!/bin/bash

# Checked for installed CLT
if [[ -e "/Library/Developer/CommandLineTools/usr/bin/git" ]]
then
  exit 0
fi

CLT_PLACEHOLDER="/tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress"
touch "${CLT_PLACEHOLDER}"

CLT_PACKAGE=$(softwareupdate -l |
  grep -B 1 "Command Line Tools" |
  awk -F"*" '/^ *\*/ {print $2}' |
  sed -e 's/^ *Label: //' -e 's/^ *//' |
  sort -V |
  tail -n1)
softwareupdate -i "${CLT_PACKAGE}"
rm -f "${CLT_PLACEHOLDER}"
if ! [[ -f "/Library/Developer/CommandLineTools/usr/bin/git" ]]
then
  if [[ -z "${COMMAND_LINE_INSTALL}" ]]
  then
    echo
    printf "Requesting user install of Xcode Command Line Tools:"
    /usr/bin/xcode-select --install
  else
    echo
    printf "Run 'xcode-select --install' to install the Xcode Command Line Tools before running a headless brew install."
    exit 1
  fi
fi
