on:
  push:
    branches:
      - "master"
    tags:
      - "v*.*.*"

name: Build Docker images

jobs:
  build-dev-image:
    name: Build development image
    if: github.ref_type == 'branch' && github.ref_name == 'master'
    runs-on: ubuntu-latest
    environment: dev

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

      - name: Docker metadata
        id: meta
        uses: docker/metadata-action@v4
        with:
          images: |
            ${{ github.repository_owner }}/tmail-web
            ghcr.io/${{ github.repository_owner }}/tmail-web
          tags: |
            type=ref,event=branch

      - name: Login to Docker Hub
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Login to GitHub Container Registry
        uses: docker/login-action@v2
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push image
        uses: docker/build-push-action@v4
        with:
          push: true
          cache-from: |
            type=gha
          cache-to: |
            type=gha
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}

  build-release-image:
    name: Build release image
    if: github.ref_type == 'tag' && startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    environment: prod

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

      - name: Docker metadata
        id: meta
        uses: docker/metadata-action@v4
        with:
          images: |
            ${{ github.repository_owner }}/tmail-web
            ghcr.io/${{ github.repository_owner }}/tmail-web
          tags: |
            type=ref,event=tag
            type=raw,value=release

      - name: Login to Docker Hub
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Login to GitHub Container Registry
        uses: docker/login-action@v2
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push image
        uses: docker/build-push-action@v4
        with:
          push: true
          cache-from: |
            type=gha
          cache-to: |
            type=gha
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
