name: Build and Push Stable Image

on:
  push:
    branches:
      - "release/**"
    tags:
      - "v*.*.*"

env:
  DOCKER_PLATFORMS: |
    linux/amd64
    linux/arm/v7
    linux/arm64

jobs:
  build-and-push-image:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v5

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3
        with:
          platforms: ${{ env.DOCKER_PLATFORMS }}

      - name: Set up Docker Buildx
        id: buildx
        uses: docker/setup-buildx-action@v3
        with:
          version: latest
          install: true
          platforms: ${{ env.DOCKER_PLATFORMS }}

      - name: Extract version
        run: |
          if [[ "$GITHUB_REF_TYPE" == "tag" ]]; then
            echo "VERSION=${GITHUB_REF_NAME#v}" >> $GITHUB_ENV
          else
            echo "VERSION=${GITHUB_REF_NAME#release/}" >> $GITHUB_ENV
          fi

      - name: Login to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKER_HUB_USERNAME }}
          password: ${{ secrets.DOCKER_HUB_TOKEN }}

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

      - name: Docker meta
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: |
            neosmemo/memos
            ghcr.io/usememos/memos
          tags: |
            type=semver,pattern={{version}},value=${{ env.VERSION }}
            type=semver,pattern={{major}}.{{minor}},value=${{ env.VERSION }}
            type=raw,value=stable
          flavor: |
            latest=false
          labels: |
            org.opencontainers.image.version=${{ env.VERSION }}

      # Frontend build.
      - uses: pnpm/action-setup@v4.1.0
        with:
          version: 10
      - uses: actions/setup-node@v5
        with:
          node-version: "22"
          cache: pnpm
          cache-dependency-path: "web/pnpm-lock.yaml"
      - run: pnpm install
        working-directory: web
      - name: Run frontend build
        run: pnpm release
        working-directory: web

      - name: Build and Push
        id: docker_build
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./scripts/Dockerfile
          platforms: ${{ env.DOCKER_PLATFORMS }}
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          build-args: |
            BUILDKIT_INLINE_CACHE=1
