# Gitea Actions workflow: build Docker image and push to a container registry
# Place secrets in the repository settings: REGISTRY (host[:port]), IMAGE_NAME, DOCKER_USERNAME, DOCKER_PASSWORD

name: Build and Publish Docker Image

on:
  push:
    branches:
      - main
  workflow_dispatch: {}

jobs:
  build-and-push:
    # Use an appropriate runner that has Docker available (self-hosted runner)
    runs-on: self-hosted
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Build and push image
        # run everything in a single shell step to keep tag calculation simple
        run: |
          set -euo pipefail
          REGISTRY="${{ secrets.REGISTRY }}"
          IMAGE_NAME="${{ secrets.IMAGE_NAME }}"
          DOCKER_USERNAME="${{ secrets.DOCKER_USERNAME }}"
          DOCKER_PASSWORD="${{ secrets.DOCKER_PASSWORD }}"

          if [ -z "$REGISTRY" ] || [ -z "$IMAGE_NAME" ]; then
            echo "Missing required secrets: REGISTRY and IMAGE_NAME must be set." >&2
            exit 1
          fi

          TAG=$(git rev-parse --short HEAD)
          IMAGE="$REGISTRY/$IMAGE_NAME:$TAG"
          LATEST="$REGISTRY/$IMAGE_NAME:latest"

          echo "Logging in to $REGISTRY"
          echo "$DOCKER_PASSWORD" | docker login "$REGISTRY" -u "$DOCKER_USERNAME" --password-stdin

          echo "Building $IMAGE (and tagging as latest)"
          docker build -t "$IMAGE" -t "$LATEST" .

          echo "Pushing $IMAGE"
          docker push "$IMAGE"

          echo "Pushing $LATEST"
          docker push "$LATEST"

        env:
          # secrets are available via ${{ secrets.<name> }} in Gitea Actions
          REGISTRY: ${{ secrets.REGISTRY }}
          IMAGE_NAME: ${{ secrets.IMAGE_NAME }}
          DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
          DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
