name: Build & publish images to the package registry for tags

on:
  release:
    types: [published]

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build:
    name: Build & publish
    runs-on: ubuntu-latest
    permissions:
      contents: write # required to upload release asset
      packages: write
    steps:
      - name: Check it out
        uses: actions/checkout@v2

      - name: Log in to container registry
        uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Yarn cache
        uses: actions/setup-node@v3
        with:
          cache: "yarn"
      - name: Install dependencies
        run: "yarn install"
      - name: Build
        run: "yarn run build"
        env:
          SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
          SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
          SENTRY_URL: ${{ secrets.SENTRY_URL }}
          SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
          VITE_APP_VERSION: ${{ github.event.release.tag_name }}
          # This appears to be necessary to stop Vite from OOMing
          # https://github.com/vitejs/vite/issues/2433
          NODE_OPTIONS: "--max-old-space-size=16384"

      - name: Create Tarball
        env:
          GITHUB_TAG_NAME: ${{ github.event.release.tag_name }}
        run: |
          tar --numeric-owner --transform "s/dist/element-call-${GITHUB_TAG_NAME}/" -cvzf element-call-${GITHUB_TAG_NAME}.tar.gz dist
      - name: Upload
        uses: alexellis/upload-assets@0.4.0
        env:
          GITHUB_TOKEN: ${{ github.token }}
        with:
          asset_paths: '["element-call-${{ github.event.release.tag_name }}.tar.gz"]'

      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@dc7b9719a96d48369863986a06765841d7ea23f6

      - name: Build and push Docker image
        uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc
        with:
          context: .
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
