# SPDX-FileCopyrightText: 2015-2024 Alexey Rochev
#
# SPDX-License-Identifier: CC0-1.0

name: Build Tremotesf for MacOS

on:
  workflow_call:
    inputs:
      release-tag:
        description: Release tag
        type: string
        required: false
        default: ''

jobs:
  build-macos:
    strategy:
      fail-fast: false
      matrix:
        architecture: ['arm64', 'x86_64']

    runs-on: macos-latest
    steps:
      - name: Add GCC problem matcher
        uses: ammaraskar/gcc-problem-matcher@master

      - name: Checkout
        uses: actions/checkout@v4
        with:
          submodules: 'recursive'

      - name: Use latest Xcode
        uses: maxim-lobanov/setup-xcode@v1
        with:
          xcode-version: latest-stable

      - name: Set up vcpkg
        uses: equeim/action-setup-vcpkg@v6
        with:
          vcpkg-root: ${{ github.workspace }}/vcpkg
          save-cache: ${{ github.event_name != 'pull_request' }}
          cache-key-tag: ${{ matrix.architecture }}

      - name: Install host dependencies
        run: |
          brew install autoconf automake libtool ninja

      - name: Build Tremotesf for ${{ matrix.architecture }} architecture
        id: build
        uses: equeim/action-cmake-build@v10
        with:
          cmake-arguments: --preset macos-${{ matrix.architecture }}-vcpkg -D TREMOTESF_ASAN=${{ inputs.release-tag == '' && 'ON' || 'OFF' }}
          package: true
        env:
          ASAN_OPTIONS: detect_leaks=0

      - name: Archive packages
        if: inputs.release-tag == ''
        uses: actions/upload-artifact@v4
        with:
          name: macos-${{ matrix.architecture }}-packages
          retention-days: ${{ github.event_name == 'push' && 7 || 3 }}
          path: |
            ${{ steps.build.outputs.build-directory }}/packaging/macos/*.dmg

      - name: Upload packages to release
        if: inputs.release-tag != ''
        run: |
          packages=(${{ steps.build.outputs.build-directory }}/packaging/macos/*.dmg)
          echo "Uploading packages ${packages[@]}"
          gh release upload '${{ inputs.release-tag }}' "${packages[@]}"
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Archive build logs
        uses: actions/upload-artifact@v4
        if: always()
        with:
          name: macos-${{ matrix.architecture }}-build-logs
          retention-days: ${{ github.event_name == 'push' && 7 || 3 }}
          path: |
            ${{ steps.build.outputs.build-directory }}/CMakeCache.txt
            ${{ steps.build.outputs.build-directory }}/compile_commands.json
            ${{ steps.build.outputs.build-directory }}/vcpkg-manifest-install.log
            ${{ steps.build.outputs.build-directory }}/CMakeFiles/CMakeConfigureLog.yaml
            ${{ env.VCPKG_ROOT }}/buildtrees/*/*.log
