name: Build all tarballs

on:
  schedule:
    - cron: '0 0 * * *'
  workflow_dispatch:

jobs:
  check-changes:
    runs-on: ubuntu-24.04
    outputs:
      has_changes: ${{ github.event_name == 'workflow_dispatch' || steps.check.outputs.has_changes }}
    steps:
    - name: Check for new commits since last successful run
      id: check
      env:
        GH_TOKEN: ${{ github.token }}
      run: |
        last=$(gh run list -R ${{ github.repository }} -w build-all.yml -b main -s success -L1 --json createdAt -q '.[0].createdAt')
        if [ -z "$last" ] || [ "$last" = "null" ] || [ "$(gh api repos/${{ github.repository }}/commits?sha=main\&since=$last\&per_page=1 | jq length)" -gt 0 ]; then
          echo "has_changes=true" >> "$GITHUB_OUTPUT"
        fi

  build-linux:
    needs: check-changes
    if: needs.check-changes.outputs.has_changes == 'true'
    strategy:
      matrix:
        include:
          - { target: x86_64,      os: ubuntu-24.04 }
          - { target: aarch64,     os: ubuntu-24.04-arm }
          - { target: arm,         os: ubuntu-24.04-arm }
          - { target: riscv64,     os: ubuntu-24.04 }
          - { target: ppc64le,     os: ubuntu-24.04 }
          - { target: s390x,       os: ubuntu-24.04 }
          - { target: loongarch64, os: ubuntu-24.04 }

    runs-on: ${{ matrix.os }}

    permissions:
      contents: read
      packages: write

    steps:
    - name: Checkout Repository
      uses: actions/checkout@v4

    - name: Install Podman
      run: sudo apt-get update && sudo apt-get install -y podman qemu-user-static

    - name: Login to GitHub Container Registry
      uses: redhat-actions/podman-login@v1
      with:
        registry: ghcr.io
        username: ${{ github.repository_owner }}
        password: ${{ secrets.GITHUB_TOKEN }}

    - name: Build a tarball
      run: ./dist.sh ${{ matrix.target }}

    - name: Upload artifact
      uses: actions/upload-artifact@v4
      with:
        name: ${{ matrix.target }}
        path: dist/mold-*.tar.gz
        compression-level: 0

  build-windows:
    needs: check-changes
    if: needs.check-changes.outputs.has_changes == 'true'
    runs-on: windows-latest
    steps:
    - name: Checkout Repository
      uses: actions/checkout@v4

    - name: Build and Archive
      shell: pwsh
      run: |
        mkdir build
        cd build
        cmake -T clangcl ..
        cmake --build . --config Release -j $Env:NUMBER_OF_PROCESSORS
        cmake --install . --config Release --prefix ../mold-install
        cd ..
        New-Item -ItemType Directory -Force dist | Out-Null
        $version = $Env:TAG -replace '^v', ''
        Compress-Archive -Path mold-install\* -DestinationPath dist\mold-$version-windows-x86_64.zip

    - name: Upload artifact
      uses: actions/upload-artifact@v4
      with:
        name: win-x86_64
        path: dist/mold-*.*
