name: Docker Release

on:
  push:
    tags:
      - v*

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Docker meta
        id: meta
        uses: docker/metadata-action@v6
        with:
          images: |
            ${{ secrets.DOCKER_REPO }}/mayswind/ezbookkeeping
          tags: |
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=raw,value=latest

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v4

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

      - name: Set up the environment
        id: setup
        run: |
          echo "build_unix_time=$(date '+%s')" >> "$GITHUB_OUTPUT"
          echo "build_date=$(date '+%Y%m%d')" >> "$GITHUB_OUTPUT"
          sed -r -i 's#FROM( --.*)? (.*:.*)?#FROM\1 ${{ secrets.DOCKER_REPO }}/mirrors/\2#g' Dockerfile
          cat >> docker/custom-backend-pre-setup.sh <<EOF
          #!/bin/sh
          ${{ vars.CUSTOM_BACKEND_PRE_SETUP }}
          EOF
          cat >> docker/custom-frontend-pre-setup.sh <<EOF
          #!/bin/sh
          ${{ vars.CUSTOM_FRONTEND_PRE_SETUP }}
          EOF
          chmod +x docker/custom-backend-pre-setup.sh
          chmod +x docker/custom-frontend-pre-setup.sh

      - name: Build and push
        uses: docker/build-push-action@v6
        with:
          file: Dockerfile
          context: .
          platforms: ${{ vars.BUILD_RELEASE_PLATFORMS }}
          push: true
          build-args: |
            RELEASE_BUILD=1
            BUILD_PIPELINE=1
            BUILD_UNIXTIME=${{ steps.setup.outputs.build_unix_time }}
            BUILD_DATE=${{ steps.setup.outputs.build_date }}
            CHECK_3RD_API=${{ vars.CHECK_3RD_API }}
            SKIP_TESTS=${{ vars.SKIP_TESTS }}
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
