name: Build and Push Reader Image

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

jobs:
  docker:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout source
        uses: actions/checkout@v4

      - name: Log in to Gitea Registry
        env:
          SERVER_URL: ${{ gitea.server_url }}
          USERNAME: ${{ gitea.actor }}
          PASSWORD: ${{ secrets.TOKEN }}
        run: |
          REGISTRY="${SERVER_URL#https://}"
          REGISTRY="${REGISTRY#http://}"
          echo "$PASSWORD" | docker login "$REGISTRY" -u "$USERNAME" --password-stdin

      - name: Build and push image
        env:
          SERVER_URL: ${{ gitea.server_url }}
          REPOSITORY: ${{ gitea.repository }}
          REF: ${{ gitea.ref }}
        run: |
          REGISTRY="${SERVER_URL#https://}"
          REGISTRY="${REGISTRY#http://}"

          if [[ "$REF" == refs/tags/v* ]]; then
            TAG="${REF#refs/tags/}"
          else
            TAG="latest"
          fi

          IMAGE="$REGISTRY/$REPOSITORY:$TAG"
          docker build --network host -f Dockerfile -t "$IMAGE" .
          docker push "$IMAGE"

          if [[ "$TAG" != "latest" ]]; then
            LATEST_IMAGE="$REGISTRY/$REPOSITORY:latest"
            docker tag "$IMAGE" "$LATEST_IMAGE"
            docker push "$LATEST_IMAGE"
          fi
