name: Build And Push Docker Image

on:
  push:
    tags:
      - "image"
  workflow_dispatch:

jobs:
  docker:
    runs-on: ubuntu-latest
    env:
      DOTNET_ROLL_FORWARD: Major
      REGISTRY: git.beging.de
      BASE_IMAGE: git.beging.de/troogs/fs-onboarding-server

    steps:
      - name: Checkout repository
        uses: actions/checkout@v6

      - name: Setup .NET SDK
        uses: actions/setup-dotnet@v5
        with:
          dotnet-version: "9.0.x"

      - name: Publish server project
        run: dotnet publish ./FoodsharingSiegen.Server/FoodsharingSiegen.Server.csproj -c Release -o ./Publish/Server

      - name: Login to Gitea registry
        run: echo "${{ secrets.REGISTRY_TOKEN }}" | docker login "${{ env.REGISTRY }}" -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin

      - name: Determine next timestamp tag
        shell: bash
        run: |
          TODAY="$(date -u +%Y%m%d)"
          i=1
          while docker manifest inspect "${BASE_IMAGE}:${TODAY}-${i}" > /dev/null 2>&1; do
            i=$((i + 1))
          done

          DATE_TAG="${TODAY}-${i}"
          echo "DATE_TAG=${DATE_TAG}" >> "$GITHUB_ENV"
          echo "Using image tag: ${DATE_TAG}"

      - name: Build docker image
        run: |
          docker build \
            -f ./Docker/dockerfile.server \
            -t "${{ env.BASE_IMAGE }}:latest" \
            -t "${{ env.BASE_IMAGE }}:${{ env.DATE_TAG }}" \
            .

      - name: Push docker images
        run: |
          docker push "${{ env.BASE_IMAGE }}:latest"
          docker push "${{ env.BASE_IMAGE }}:${{ env.DATE_TAG }}"
