#!/bin/bash

CONFIG="${1:-Release}"
PLATFORM="${2:-x64}"

# Validate configuration
if [[ "$CONFIG" != "Debug" && "$CONFIG" != "Release" ]]; then
    echo "Error: Invalid configuration '$CONFIG'. Use 'Debug' or 'Release'."
    exit 1
fi

BUILD_RESULT=1

# Find a build tool
build_with_msbuild() {
    local VSWHERE="/c/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe"
    [[ ! -f "$VSWHERE" ]] && return 1

    local VS_PATH
    VS_PATH=$("$VSWHERE" -latest -requires Microsoft.Component.MSBuild -property installationPath)
    [[ -z "$VS_PATH" ]] && return 1

    local MSBUILD="$VS_PATH/MSBuild/Current/Bin/MSBuild.exe"
    [[ ! -f "$MSBUILD" ]] && return 1

    echo "Building with MSBuild [$CONFIG|$PLATFORM]"
    "$MSBUILD" boreal.slnx -p:Configuration="$CONFIG" -p:Platform="$PLATFORM" -m -verbosity:minimal -clp:ForceNoAlign
    BUILD_RESULT=$?
    return 0
}

build_with_make() {
    command -v make &>/dev/null || return 1
    [[ -f Makefile || -d build ]] || return 1

    local cfg
    cfg=$(echo "${CONFIG}_${PLATFORM}" | tr '[:upper:]' '[:lower:]')

    echo "Building with Make [$cfg]"
    if [[ -f build/Makefile ]]; then
        make -C build config="$cfg" -j"$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)"
    else
        make config="$cfg" -j"$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)"
    fi
    BUILD_RESULT=$?
    return 0
}

build_with_xcodebuild() {
    command -v xcodebuild &>/dev/null || return 1
    ls *.xcworkspace &>/dev/null || return 1

    echo "Building with xcodebuild [$CONFIG]"
    xcodebuild -workspace boreal.xcworkspace -scheme boreal -configuration "$CONFIG"
    BUILD_RESULT=$?
    return 0
}

# Try build tools in order of preference
if [[ -f boreal.slnx ]] && build_with_msbuild; then
    :
elif build_with_make; then
    :
elif build_with_xcodebuild; then
    :
else
    echo "Error: No supported build tool found."
    echo "Supported: MSBuild (Windows), Make (any), xcodebuild (macOS)"
    exit 1
fi

if [[ $BUILD_RESULT -eq 0 ]]; then
    echo "Build complete."
else
    echo "Build failed with code $BUILD_RESULT"
fi

function pause(){
   read -p "$*"
}

read -t 5 -n 1 -p "Press any key in 5 seconds to keep window open.." key
if [[ $? -gt 128 ]] ; then
    echo -e "\nWindow exiting.."
else
    echo ""
    pause 'Key pressed. Keeping window open. Press [Enter] to close..'
fi

# return exit code 0 here as alternative to enabling force-close on terminal
exit $BUILD_RESULT