name: Build and Push Backend

on:
  push:
    branches: [ master, main ]
    paths:
      - 'docker/**'
      - 'play-admin/**'
      - 'play-common/**'
      - 'play-generator/**'
      - 'pom.xml'
  workflow_dispatch: {}

jobs:
  docker:
    runs-on: docker
    container:
      image: debian:bookworm-slim
      # act_runner already mounts the Docker socket; avoid duplicating it
      options: --privileged
    steps:
      - name: Prepare tools via Tencent mirrors (apt)
        shell: bash
        run: |
          set -euo pipefail
          if [ -f /etc/apt/sources.list ]; then
            sed -i 's|deb.debian.org|mirrors.tencent.com|g; s|security.debian.org|mirrors.tencent.com|g' /etc/apt/sources.list
          fi
          if [ -f /etc/apt/sources.list.d/debian.sources ]; then
            sed -i 's|http://deb.debian.org/debian|http://mirrors.tencent.com/debian|g; s|http://security.debian.org/debian-security|http://mirrors.tencent.com/debian-security|g' /etc/apt/sources.list.d/debian.sources
          fi
          apt-get update
          DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
            ca-certificates curl git docker.io docker-buildx-plugin
          docker version
          git --version

      - name: Checkout repository (git)
        env:
          REPO: ${{ github.repository }}
          SERVER: ${{ github.server_url }}
          SHA: ${{ github.sha }}
        shell: bash
        run: |
          set -euo pipefail
          echo "Cloning $SERVER/$REPO at $SHA"
          git clone --depth=1 "$SERVER/$REPO" /workspace
          cd /workspace
          git fetch --depth=1 origin "$SHA" || true
          git checkout -q "$SHA" || true

      - name: Build and push to local registry
        env:
          REGISTRY: 127.0.0.1:5000
          TAG: ${{ github.sha }}
        shell: bash
        run: |
          cd /workspace/peipei-backend
          export DOCKER_BUILDKIT=1
          docker build \
            --build-arg MIRROR_REG=docker.m.daocloud.io/library/ \
            -f docker/Dockerfile \
            -t ${REGISTRY}/peipei/backend:${TAG} \
            -t ${REGISTRY}/peipei/backend:latest \
            .
          docker push ${REGISTRY}/peipei/backend:${TAG}
          docker push ${REGISTRY}/peipei/backend:latest
