name: Docker Build and Release

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

permissions:
  contents: read
  packages: write

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    outputs:
      tag: ${{ steps.meta.outputs.tag }}
    steps:
      - name: Checkout
        uses: https://gitea.com/actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Set image meta
        id: meta
        run: |
          TAG="${GITHUB_REF#refs/tags/}"
          echo "tag=$TAG" >> $GITHUB_OUTPUT

      - name: Set registry host
        id: registry
        run: |
          host="${GITHUB_SERVER_URL#https://}"
          host="${host#http://}"
          echo "host=$host" >> $GITHUB_OUTPUT

      - name: Check REGISTRY_TOKEN
        run: |
          if [ -z "${{ secrets.REGISTRY_TOKEN }}" ]; then
            echo "::error::REGISTRY_TOKEN secret is not set. Add it in repository or organization settings."
            exit 1
          fi

      - name: Login to Gitea Container Registry
        run: |
          host="${{ steps.registry.outputs.host }}"
          echo "${{ secrets.REGISTRY_TOKEN }}" | docker login "$host" -u "${{ github.actor }}" --password-stdin

      - name: Build and push Docker image
        run: |
          host="${{ steps.registry.outputs.host }}"
          repository=$(echo "${{ github.repository }}" | tr '[:upper:]' '[:lower:]')
          IMAGE="$host/$repository"
          TAG="${{ steps.meta.outputs.tag }}"
          docker build -t "$IMAGE:$TAG" -t "$IMAGE:latest" .
          docker push "$IMAGE:$TAG"
          docker push "$IMAGE:latest"

  release:
    runs-on: ubuntu-latest
    needs: build-and-push
    permissions:
      contents: write
    steps:
      - name: Checkout
        uses: https://gitea.com/actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Generate release notes
        id: notes
        run: |
          TAG="${{ needs.build-and-push.outputs.tag }}"
          PREV=""
          for t in $(git tag -l --sort=-v:refname "v*"); do
            [ "$t" = "$TAG" ] && continue
            PREV="$t"
            break
          done
          if [ -n "$PREV" ]; then
            git log "$PREV..$TAG" --pretty=format:"- %s (%h)" --no-merges > release_notes.md
          else
            (git log -1 --pretty=format:"- %s (%h)" 2>/dev/null || echo "Initial release") > release_notes.md
          fi

      - name: Create Release
        uses: https://gitea.com/actions/gitea-release-action@v1
        with:
          tag_name: ${{ needs.build-and-push.outputs.tag }}
          body_path: release_notes.md
