# Workflow derived from https://github.com/r-lib/actions/tree/master/examples
# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help
on:
  push:
    tags:
      - '*.*-*'
  workflow_dispatch:

name: binary-build

env:
  release_name: ${{ vars.repo_name }}_${{ github.ref_name }}

jobs:
  source_build:          
    runs-on: ubuntu-latest
    name: Build source tarball
    strategy:
      fail-fast: false

    steps:
      - uses: actions/checkout@v4

      - uses: r-lib/actions/setup-r@v2
        with:
          r-version: latest

      - uses: r-lib/actions/setup-r-dependencies@v2
        with:
          extra-packages: |
            any::pkgbuild

      - name: Build source tarball
        run: |
          R CMD build --force --no-manual --resave-data --compact-vignettes=both --md5 .
          mkdir -p ${{ github.workspace }}/artifacts
          cp ${{ env.release_name }}.tar.gz ${{ github.workspace }}/artifacts

      - uses: actions/upload-artifact@v4
        with:
          name: source_tarball
          path: ${{ github.workspace }}/artifacts/${{ env.release_name }}.tar.gz

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

    name: ${{ matrix.config.os }} (${{ matrix.config.r }})

    strategy:
      fail-fast: false
      matrix:
        config:
          - {os: macOS-latest,   r: 'release', ext: "tgz"}
          - {os: windows-latest, r: 'release', ext: "zip"}

    steps:
      - uses: actions/checkout@v4

      - uses: r-lib/actions/setup-r@v2
        with:
          r-version: ${{ matrix.config.r }}

      - uses: r-lib/actions/setup-r-dependencies@v2
        with:
          extra-packages: |
            any::pkgbuild

      - name: Build binary
        run: pkgbuild::build(binary=TRUE,manual=TRUE)
        shell: Rscript {0}

      - name: Copy tarball
        run: |
          mkdir -p ${{ github.workspace }}/artifacts
          cp ../${{ env.release_name }}.${{ matrix.config.ext }} ${{ github.workspace }}/artifacts

      - uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.config.os }}-${{ matrix.config.r }}
          path: ${{ github.workspace }}/artifacts/${{ env.release_name }}.${{ matrix.config.ext }}

# Workflow derived from https://github.com/marketplace/actions/create-release
  create_release:
    needs: [ source_build, binary_build ]
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
    - uses: actions/checkout@v4
    - uses: actions/download-artifact@v4
      with:
        path: artifacts
    - uses: ncipollo/release-action@v1
      with:
        draft: true
        artifacts: "artifacts/*/*"
