name: Build libheif for linux

on:
  push:
    paths:
      - '.github/workflows/libheif-linux.yml'
      - '.github/scripts/libheif-linux.sh'
    branches:
      - main
  pull_request:
    paths:
      - '.github/workflows/libheif-linux.yml'
      - '.github/scripts/libheif-linux.sh'
  workflow_dispatch:

# Cancel previous runs of the same workflow on the same branch.
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build-libheif-linux:
    strategy:
      fail-fast: true
      matrix:
        settings:
          - host: ubuntu-latest
            target: x86_64-linux-gnu
          - host: ubuntu-latest
            target: aarch64-linux-gnu
          - host: ubuntu-latest
            target: x86_64-linux-musl
          - host: ubuntu-latest
            target: aarch64-linux-musl
    name: Build LibHeif Linux ${{ matrix.settings.target }}
    runs-on: ${{ matrix.settings.host }}
    defaults:
      run:
        shell: bash
    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Build libheif
        run: |
          set -euxo pipefail

          sudo .github/scripts/libheif-linux.sh ${{ matrix.settings.target }}

          sudo chown -R "$(id -u):$(id -g)" .github/scripts/src/prefix

          # Remove uneeded files
          rm -rf .github/scripts/src/prefix/{share,lib/{cmake,pkgconfig}}
          find .github/scripts/src/prefix -empty -delete

          find .github/scripts/src/prefix -name 'libheif.so*' -exec realpath -s --relative-to=.github/scripts/src/prefix {} + \
          | xargs env XZ_OPT='-T0 -9' tar -cJf "libheif-${{ matrix.settings.target }}.tar.xz" -C .github/scripts/src/prefix include/libheif

      - name: Publish libheif
        uses: actions/upload-artifact@v3
        with:
          name: libheif-${{ matrix.settings.target }}
          path: libheif-${{ matrix.settings.target }}.tar.xz
          if-no-files-found: error
