name: Build and Push Docker Image

on:
  push:
    branches: [main]
    tags: ["v*"]

env:
  REGISTRY: http://10.10.1.132:3000
  IMAGE_NAME: marwan/hh

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

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

      - name: Login to Gitea Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ gitea.actor }}
          password: ${{ secrets.REGISTRY_TOKEN }}

      - name: Determine tags
        id: meta
        run: |
          IMAGE="${REGISTRY}/${IMAGE_NAME}"
          BRANCH="${GITHUB_REF_NAME}"
          SHA=$(echo "${GITHUB_SHA}" | cut -c1-7)

          TAGS=""

          if [[ "${GITHUB_REF}" == refs/tags/v* ]]; then
            VERSION="${GITHUB_REF_NAME}"
            TAGS="${IMAGE}:${VERSION}"
            echo "Building release: ${VERSION}"
          elif [[ "${BRANCH}" == "main" ]]; then
            TAGS="${IMAGE}:latest,${IMAGE}:${SHA}"
            echo "Building main: latest + ${SHA}"
          elif [[ "${BRANCH}" == "staging" ]]; then
            TAGS="${IMAGE}:staging,${IMAGE}:staging-${SHA}"
            echo "Building staging: staging + staging-${SHA}"
          fi

          echo "tags=${TAGS}" >> "$GITHUB_OUTPUT"
          echo "Pushing tags: ${TAGS}"

      - name: Build and push
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./Dockerfile
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache
          cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache,mode=max
