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

# Build Nebula Browser (macOS).
# Usage:
#   ./build.sh              - configure + Release build
#   ./build.sh Debug        - configure + Debug build
#   ./build.sh Release      - configure + Release build
#   ./build.sh configure    - configure only
#   ./build.sh clean        - remove the build folder

cd "$(dirname "$0")"

if [[ "${1:-}" == "clean" ]]; then
    echo "Removing build/ ..."
    rm -rf build
    echo "Done."
    exit 0
fi

CONFIG="Release"
case "${1:-}" in
    Debug|debug) CONFIG="Debug" ;;
    Release|release) CONFIG="Release" ;;
esac

if [[ ! -f "thirdparty/cef/cmake/FindCEF.cmake" ]]; then
    echo "ERROR: CEF not found at thirdparty/cef/"
    echo "Download a macOS CEF standard binary distribution and extract it"
    echo "so that thirdparty/cef/cmake/FindCEF.cmake exists."
    exit 1
fi

case "$(uname -m)" in
    arm64) PROJECT_ARCH="arm64" ;;
    x86_64) PROJECT_ARCH="x86_64" ;;
    *)
        echo "ERROR: Unsupported architecture: $(uname -m)"
        exit 1
        ;;
esac

echo "Configuring CMake (arch=$PROJECT_ARCH, config=$CONFIG)..."
cmake -B build \
    -DPROJECT_ARCH="$PROJECT_ARCH" \
    -DCMAKE_BUILD_TYPE="$CONFIG" \
    || { echo "Configure failed."; exit 1; }

if [[ "${1:-}" == "configure" ]]; then
    echo "Configure complete."
    exit 0
fi

echo "Building $CONFIG..."
cmake --build build --config "$CONFIG" \
    || { echo "Build failed."; exit 1; }

APP_PATH=""
for candidate in "build/$CONFIG/NebulaBrowser.app" "build/NebulaBrowser.app"; do
    if [[ -d "$candidate" ]]; then
        APP_PATH="$candidate"
        break
    fi
done

echo ""
if [[ -n "$APP_PATH" ]]; then
    echo "Build succeeded: $APP_PATH"
else
    echo "Build succeeded (app bundle location may vary under build/)"
fi
