name: Build and Push Container

on:
  push:
    branches:
      - master
      - main
    tags:
      - v*
  workflow_dispatch:

env:
  REGISTRY: gitea.wayfinderak.com
  IMAGE_NAME: wayfinderak/goff

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

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

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

      - name: Log in to Gitea registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ secrets.REGISTRY_USERNAME }}
          password: ${{ secrets.REGISTRY_PASSWORD }}

      - name: Prepare image tags
        id: prep
        shell: bash
        run: |
          short_sha="${GITHUB_SHA::7}"
          tags="${REGISTRY}/${IMAGE_NAME}:sha-${short_sha}"

          if [[ "${GITHUB_REF_TYPE}" == "branch" && ("${GITHUB_REF_NAME}" == "master" || "${GITHUB_REF_NAME}" == "main") ]]; then
            tags+=$'\n'"${REGISTRY}/${IMAGE_NAME}:latest"
          fi

          if [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then
            version="${GITHUB_REF_NAME#v}"
            tags+=$'\n'"${REGISTRY}/${IMAGE_NAME}:${version}"
          fi

          {
            echo 'tags<<EOF'
            echo "$tags"
            echo 'EOF'
          } >> "$GITHUB_OUTPUT"

      - name: Build and push image
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          platforms: linux/amd64,linux/arm64
          tags: ${{ steps.prep.outputs.tags }}
