name: macOS X86-64 Build
on: [push, pull_request]

jobs:
  build:
    runs-on: macos-13
    permissions:
      actions: write
    steps:
      - uses: actions/checkout@v4

      - name: Install dependencies
        run: brew install cmake allegro fluid-synth mad enet dylibbundler

      - name: Build
        run: ./scripts/build-macos.sh

      - name: Bundle libs
        run: ./scripts/bundle-libs-macos.sh

      - name: Copy OS specific files
        run: cp -r ./dist-os-specific/macos/* ./dist

      - name: Test executable
        run: |
          brew uninstall --force --ignore-dependencies argtable sdl2 dumb libogg flac libpng freetype libvorbis ca-certificates openssl@3 opus opusfile physfs theora giflib jpeg-turbo xz lz4 zstd libtiff webp pcre2 gettext glib lame mpg123 libsndfile portaudio readline allegro fluid-synth mad enet
          cd dist
          ./dunedynasty | grep "data directory"

      - name: Zip dist folder
        run: |
          cd dist
          zip -r dist.zip .

      - name: Delete Old Artifacts
        uses: actions/github-script@v7
        id: artifact
        with:
          script: |
            const res = await github.rest.actions.listArtifactsForRepo({
                owner: context.repo.owner,
                repo: context.repo.repo,
            })

            res.data.artifacts
                .filter(({ name }) => name === 'macos-x86-64-build')
                .forEach(({ id }) => {
                  github.rest.actions.deleteArtifact({
                      owner: context.repo.owner,
                      repo: context.repo.repo,
                      artifact_id: id,
                  })
                })
                
      - name: Upload Artifact
        uses: actions/upload-artifact@v4
        with:
          name: macos-x86-64-build
          path: dist/dist.zip
