name: Mars CD for PyPI

on:
  push:
    tags:
      - '*'

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build:
    name: Build wheels on ${{ matrix.os }} for ${{ matrix.arch }}
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]
        arch: [auto]
        include:
          - os: ubuntu-latest
            arch: aarch64
          - os: macos-latest
            arch: universal2

    steps:
      - name: Check out code
        uses: actions/checkout@v2

      - name: Build web for Linux
        if: ${{ matrix.os == 'ubuntu-latest' }}
        run: |
          git reset --hard
          pip install -r ci/requirements-wheel.txt
          python setup.py build_web

      - name: Set up QEMU
        if: ${{ matrix.arch == 'aarch64' }}
        uses: docker/setup-qemu-action@v1

      - name: Build wheels
        uses: pypa/cibuildwheel@v2.3.1
        env:
          CIBW_BEFORE_BUILD: git reset --hard && pip install -r ci/requirements-wheel.txt
          CIBW_ARCHS: ${{ matrix.arch }}
          CIBW_SKIP: pp* *-musllinux* cp36-* cp310-win32 *i686 cp310-manylinux_x86_64
          CIBW_MANYLINUX_X86_64_IMAGE: manylinux1
          CIBW_MANYLINUX_AARCH64_IMAGE: manylinux2014

      - name: Build wheels (Python 3.10 x86_64)
        if: ${{ matrix.os == 'ubuntu-latest' && matrix.arch == 'auto'}}
        uses: pypa/cibuildwheel@v2.3.1
        env:
          CIBW_BEFORE_BUILD: git reset --hard && pip install -r ci/requirements-wheel.txt
          CIBW_BUILD: cp310-manylinux_x86_64
          CIBW_MANYLINUX_X86_64_IMAGE: manylinux2014

      - name: Build source
        if: ${{ matrix.os == 'ubuntu-latest' && matrix.arch == 'auto' }}
        run: |
          git reset --hard
          pip install -r ci/requirements-wheel.txt
          python setup.py sdist --formats=gztar --dist-dir=./wheelhouse

      - name: Release to pypi
        shell: bash
        env:
          PYPI_USR: ${{ secrets.PYPI_USERNAME }}
          PYPI_PWD: ${{ secrets.PYPI_PASSWORD }}
        run: |
          if [[ "$GITHUB_REPOSITORY" == "mars-project/mars" ]]; then
            PYPI_REPO="https://upload.pypi.org/legacy/"
          else
            PYPI_REPO="https://test.pypi.org/legacy/"
          fi
          echo "[distutils]"             > ~/.pypirc
          echo "index-servers ="        >> ~/.pypirc
          echo "    pypi"               >> ~/.pypirc
          echo "[pypi]"                 >> ~/.pypirc
          echo "repository=$PYPI_REPO"  >> ~/.pypirc
          echo "username=$PYPI_USR"     >> ~/.pypirc
          echo "password=$PYPI_PWD"     >> ~/.pypirc
          python -m pip install twine
          python -m twine upload -r pypi --skip-existing wheelhouse/*

      - name: Upload artifacts to github
        uses: actions/upload-artifact@v1
        with:
          name: wheels
          path: ./wheelhouse
