#!/usr/bin/env bash
set -euo pipefail

run() { echo "==> $*"; "$@"; }

if xcode-select -p >/dev/null 2>&1 && command -v xcrun >/dev/null 2>&1; then
    echo "Apple Command Line Tools already installed."
    exit 0
fi

if command -v softwareupdate >/dev/null 2>&1; then
    label="$(
        softwareupdate --list 2>/dev/null \
            | sed -n 's/^[[:space:]]*[*-][[:space:]]*Label:[[:space:]]*//p' \
            | grep -E 'Command Line Tools|Command Line Developer Tools' \
            | tail -n1
    )"
    if [ -n "${label:-}" ]; then
        run sudo softwareupdate --install "$label" --verbose
        [ -d /Library/Developer/CommandLineTools ] && run sudo xcode-select --switch /Library/Developer/CommandLineTools
    fi
fi

if ! xcode-select -p >/dev/null 2>&1; then
    echo "Requesting Apple Command Line Tools installer..."
    xcode-select --install || true
    echo "Finish the Apple installer, then rerun your FreeBASIC build."
fi
