#!/bin/zsh

# Author: Sean Holden
# Date: 06.2022
# Copyright FileWave AG
# Provided by Professional Services

# If no version supplied as $1, then read the output of Software Update and use the greatest value reported

major=0
minor=0
catalog_counter=0

# Software update may report multiple versions.  Grab the highest available
function greatest_version {

        while [ $# -gt 0 ]
        do
                this_major=${1%%.*}
                this_minor=${1##*.}

                if [ $this_major -lt $major ]
                then
                        shift
                        continue
                fi

                if [ $this_major -eq $major ]
                then
                        if [ $this_minor -gt $minor ]
                        then
                                minor=$this_minor
                                shift
                                continue
                        fi
                fi

                if [ $this_major -gt $major ]
                then
                        major=$this_major
                        minor=$this_minor
                        shift
                        continue
                fi

                shift
        done
}

# Do not instal if Xcode has installed it
commandline_installed=$(xcrun -f strings &>/dev/null)
if [ $? -eq 0 ] 
then
	echo "Command line tools already installed, exiting..."
	exit 0
fi

# Run update
touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
version=$(softwareupdate -l 2>/dev/null | awk -F "-" '/\* Label: Command Line Tools for Xcode/ {print $NF}')
# update_required=$(softwareupdate -l | awk '/\* Label: Command Line Tools for Xcode/{ sub(/^[[:blank:]]*([^[:blank:]]+[[:blank:]]+){2}/,""); print}')

echo "Found..."
echo "$version"

if [ $1 ]
then
	update_required="Command Line Tools for Xcode-$1"
else
	greatest_version $version
	update_required="Command Line Tools for Xcode-$major.$minor"
fi

echo "#update_required"

if [ $major -ne 0 ]
then
	softwareupdate -i "$update_required"
	rm /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
fi

exit 0
