name: macOS builds

on: [push, pull_request]

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build_macos:
    name: ${{ matrix.conf.name }} (${{ matrix.conf.arch }})
    runs-on: ${{ matrix.conf.host }}
    if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name != github.repository
    strategy:
      fail-fast: false
      matrix:
        conf:
          - name: Clang
            host: macos-13
            arch: x86_64
            needs_deps: true
            build_flags: -Denable_debugger=normal
            brew_path: /usr/local/homebrew
            max_warnings: 80

#          - name: GCC 12
#            host: macos-13
#            arch: x86_64
#            needs_deps: true
#            packages: gcc@12
#            build_flags: -Dbuildtype=debug -Dunit_tests=disabled --native-file=.github/meson/native-gcc-12.ini
#            brew_path: /usr/local/homebrew
#            max_warnings: 0

          - name: Clang
            host: [self-hosted, macOS, arm64, debug-builds]
            arch: arm64
            needs_deps: false
            packages: meson
            build_flags: -Dbuildtype=debug
            brew_path: /opt/homebrew
            run_tests: true
            max_warnings: 0

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          submodules: false

      # Let self-hosted runners, which don't need_deps, leverage their own ccache.
      - name:  Add the ccache environment to GitHub-hosted runners
        if:    matrix.conf.needs_deps
        shell: bash
        run: |
          set -eu
          echo 'CCACHE_DIR="${{ github.workspace }}/.ccache"' >> $GITHUB_ENV
          echo 'CCACHE_MAXSIZE="64M"' >> $GITHUB_ENV
          echo 'CCACHE_COMPRESS="true"' >> $GITHUB_ENV

      - name:  Prepare brew and compiler caches
        if:    matrix.conf.needs_deps
        id:    prep-caches
        shell: bash
        run: |
          set -eu
          BREW_DIR="$(brew --cache)"
          DISCARD_DIR="${{ github.workspace }}/discard"
          mkdir -p "$DISCARD_DIR"
          mv -f "$BREW_DIR"/* "$DISCARD_DIR" || true
          mkdir -p "$CCACHE_DIR"
          echo "brew_dir=$BREW_DIR"     >> $GITHUB_OUTPUT
          echo "ccache_dir=$CCACHE_DIR" >> $GITHUB_OUTPUT
          echo "today=$(date +%F)"      >> $GITHUB_OUTPUT
          echo "name_hash=$(echo '${{ matrix.conf.name }} ${{ matrix.conf.arch }}' | shasum | cut -b-8)" >> $GITHUB_OUTPUT

      - uses:  actions/cache@v3.3.2
        if:    matrix.conf.needs_deps
        with:
          path: ${{ steps.prep-caches.outputs.brew_dir }}
          key:  brew-cache-${{ matrix.conf.arch }}-${{ steps.prep-caches.outputs.today }}-2
          restore-keys: brew-cache-${{ matrix.conf.arch }}-

      - name: Install C++ compiler and libraries
        if:   matrix.conf.needs_deps
        run: |
          arch -arch=${{ matrix.conf.arch }} brew unlink openssl@1.1 || true
          rm -f /usr/local/bin/openssl || true
          arch -arch=${{ matrix.conf.arch }} brew install --overwrite openssl@3 || true
          arch -arch=${{ matrix.conf.arch }} brew link --overwrite openssl@3 || true
          arch -arch=${{ matrix.conf.arch }} brew install --overwrite \
            ${{ matrix.conf.packages }} \
            $(cat packages/macos-12-brew.txt) || true

      - uses:  actions/cache@v3.3.2
        if:    matrix.conf.needs_deps
        with:
          path: ${{ steps.prep-caches.outputs.ccache_dir }}
          key:  ccache-macos-debug-${{ steps.prep-caches.outputs.name_hash }}-${{ steps.prep-caches.outputs.today }}-2
          restore-keys: |
            ccache-macos-debug-${{ steps.prep-caches.outputs.name_hash }}-
            ccache-macos-debug-

      - name: Cache subprojects
        id:   cache-subprojects
        uses: actions/cache@v3.3.2
        with:
          path: subprojects.tar
          key: subprojects-${{ hashFiles('subprojects/*.wrap') }}-1
          enableCrossOsArchive: true

      - if:   steps.cache-subprojects.outputs.cache-hit != 'true'
        name: Generate subprojects cache
        run:  scripts/fetch-and-tar-subprojects.sh

      - name: Extract subprojects cache
        run:  scripts/extract-subprojects-tar.sh

      - name: Setup and build
        run: |
          set -xo pipefail
          export PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
          eval "$(${{ matrix.conf.brew_path }}/bin/brew shellenv)"
          ./scripts/log-env.sh
          ./scripts/retry_command.sh 3 meson setup ${{ matrix.conf.build_flags }} build
          meson compile -C build 2>&1 | tee build.log

      - name: Run tests
        if:   matrix.conf.run_tests
        run: |
          export PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
          eval "$(${{ matrix.conf.brew_path }}/bin/brew shellenv)"
          meson test --num-processes 128 -t 0 -C build --print-errorlogs

      - name: Summarize warnings
        if:   matrix.conf.run_tests != true
        env:
          MAX_WARNINGS: ${{ matrix.conf.max_warnings }}
        run:  python3 ./scripts/count-warnings.py -lf build.log

  build_macos_release:
    name: Release build (${{ matrix.runner.arch }})
    runs-on: ${{ matrix.runner.host }}
    if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name != github.repository
    env:
      MACOSX_DEPLOYMENT_TARGET: ${{ matrix.runner.minimum_deployment }}

    strategy:
      matrix:
        runner:
          - host: [self-hosted, macOS, X64, release-builds]
            arch: x86_64
            build_flags: -Db_lto=true -Db_lto_threads=4
            brew_path: /usr/local/homebrew
            minimum_deployment: '10.15'
            needs_deps: false
            needs_libintl_workaround: false

          - host: [self-hosted, macOS, arm64, release-builds]
            arch: arm64
            brew_path: /opt/homebrew
            minimum_deployment: '11.0'
            needs_deps: false

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          submodules: false

      # Let self-hosted runners, which don't need_deps, leverage their own ccache.
      - name:  Add the ccache environment to GitHub-hosted runners
        if:    matrix.runner.needs_deps
        shell: bash
        run: |
          set -eu
          echo 'CCACHE_DIR="${{ github.workspace }}/.ccache"' >> $GITHUB_ENV
          echo 'CCACHE_MAXSIZE="128M"' >> $GITHUB_ENV
          echo 'CCACHE_COMPRESS="true"' >> $GITHUB_ENV
          echo 'CCACHE_SLOPPINESS="pch_defines,time_macros"' >> $GITHUB_ENV

      - name:  Prepare brew and compiler caches
        if:    matrix.runner.needs_deps
        id:    prep-caches
        shell: bash
        run: |
          set -eu
          BREW_DIR="$(brew --cache)"
          DISCARD_DIR="${{ github.workspace }}/discard"
          mkdir -p "$DISCARD_DIR"
          mv -f "$BREW_DIR"/* "$DISCARD_DIR"
          mkdir -p "$CCACHE_DIR"
          echo "brew_dir=$BREW_DIR"     >> $GITHUB_OUTPUT
          echo "ccache_dir=$CCACHE_DIR" >> $GITHUB_OUTPUT
          echo "today=$(date +%F)"      >> $GITHUB_OUTPUT

      - uses:  actions/cache@v3.3.2
        if:    matrix.runner.needs_deps
        with:
          path: ${{ steps.prep-caches.outputs.brew_dir }}
          key:  brew-cache-${{ matrix.runner.arch }}-${{ steps.prep-caches.outputs.today }}-2
          restore-keys: brew-cache-${{ matrix.runner.arch }}-

      - name: Install C++ compiler and libraries
        if:   matrix.runner.needs_deps
        run: >-
          brew install --overwrite librsvg tree ccache libpng meson opusfile sdl2 sdl2_net speexdsp

      - uses:  actions/cache@v3.3.2
        if:    matrix.runner.needs_deps
        with:
          path: ${{ steps.prep-caches.outputs.ccache_dir }}
          key:  ccache-macos-release-${{ matrix.runner.arch }}-${{ steps.prep-caches.outputs.today }}-2
          restore-keys: ccache-macos-release-${{ matrix.runner.arch }}-

      - name: Cache subprojects
        id: cache-subprojects
        uses: actions/cache@v3.3.2
        with:
          path: subprojects.tar
          key:  subprojects-${{ hashFiles('subprojects/*.wrap') }}-1
          enableCrossOsArchive: true

      - if:   steps.cache-subprojects.outputs.cache-hit != 'true'
        name: Generate subprojects cache
        run:  scripts/fetch-and-tar-subprojects.sh

      - name: Extract subprojects cache
        run:  scripts/extract-subprojects-tar.sh

      - name: Log environment
        run:  arch -arch=${{ matrix.runner.arch }} ./scripts/log-env.sh

      - name: Inject version string
        run: |
          set -x
          git fetch --prune --unshallow
          git fetch --all --tags --force
          export VERSION=$(git describe --abbrev=0)
          echo "VERSION=$VERSION" >> $GITHUB_ENV

      - name: Setup and build release
        run: |
          set -x
          eval "$(${{ matrix.runner.brew_path }}/bin/brew shellenv)"
          meson setup \
            ${{ matrix.runner.build_flags }} \
            -Ddefault_library=static \
            -Dwrap_mode=forcefallback \
            -Dtry_static_libs=sdl2,sdl2_net \
            -Duse_zlib_ng=sse2,ssse3,neon \
            build
          meson compile -C build

      - name: Upload binary
        uses: actions/upload-artifact@v4.3.1
        with:
          name: dosbox-${{ matrix.runner.arch }}
          path: build/dosbox
          overwrite: true

      - name: Upload resources
        uses: actions/upload-artifact@v4.3.1
        with:
          name: Resources
          path: Resources
          overwrite: true

  publish_universal_build:
    name: Publish universal build
    needs: build_macos_release
    runs-on: macos-12
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          submodules: false

      - name: Inject version string
        run: |
          set -x
          git fetch --prune --unshallow
          git fetch --all --tags --force
          export VERSION=$(git describe --abbrev=0)
          echo "VERSION=$VERSION" >> $GITHUB_ENV

      - name: Install brew depedencies
        run: HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=1 brew install --overwrite librsvg

      - name: Download binaries
        uses: actions/download-artifact@v4.1.3

      - name: Package
        run: |
          mv Resources ../
          ./scripts/create-package.sh \
            -p macos \
            -v "${{ env.VERSION }}" \
            -f \
            "$(pwd)" \
            "$(pwd)"

      - name: Create dmg
        run: |
          ln -s /Applications dist/

          codesign -s "-" "dist/DOSBox Staging.app" --force --deep -v

          hdiutil create \
              -volname "DOSBox Staging" \
              -srcfolder dist \
              -ov -format UDZO "dosbox-staging-macOS-${{ env.VERSION }}.dmg"

      - name:  Clam AV scan
        id:    prep-clamdb
        shell: bash
        run: |
          brew install --overwrite clamav
          export CLAMDB_DIR="/usr/local/Cellar/clamav"
          clamscan --heuristic-scan-precedence=yes --recursive --infected dist || true

      - name: Upload disk image
        uses: actions/upload-artifact@v4.3.1
        # GitHub automatically zips the artifacts, and there's no option
        # to skip it or upload a file only.
        with:
          name: dosbox-staging-macOS-universal
          path: dosbox-staging-macOS-${{ env.VERSION }}.dmg
          overwrite: true

  # This job exists only to publish an artifact with version info when building
  # from main branch, so snapshot build version will be visible on:
  # https://dosbox-staging.github.io/downloads/devel/
  #
  publish_additional_artifacts:
    name: Publish additional artifacts
    needs: build_macos_release
    runs-on: macos-13
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: false

      - name: Generate changelog
        run: |
          set +x
          git fetch --prune --unshallow
          git fetch --all --tags --force
          VERSION=$(git describe --abbrev=0)
          echo "VERSION=$VERSION" >> $GITHUB_ENV
          NEWEST_TAG=$(git describe --abbrev=0)
          git log "$NEWEST_TAG..HEAD" > changelog-$VERSION.txt

      - uses: actions/upload-artifact@v4.3.1
        with:
          # Keep exactly this artifact name; it's being used to propagate
          # version info via GitHub REST API
          name: changelog-${{ env.VERSION }}.txt
          path: changelog-${{ env.VERSION }}.txt
          overwrite: true
