name: Release

on:
  push:
    branches:
      - main

permissions:
  contents: write
  issues: write
  pull-requests: write
  id-token: write
  packages: write

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GH_TOKEN }}

      - name: Set up Bun
        uses: oven-sh/setup-bun@v2
        with:
          bun-version: latest

      - name: Install dependencies
        run: bun install --frozen-lockfile

      - name: Lint
        run: bun run lint

      - name: Type check
        run: bun run build

      - name: Run tests
        run: bun test

      - name: Run semantic-release
        id: semantic
        uses: codfish/semantic-release-action@v5
        env:
          GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
          HUSKY: 0
          HUSKY_SKIP_HOOKS: 1

      # Docker build and push
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to GitHub Container Registry
        if: steps.semantic.outputs.new-release-published == 'true'
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.repository_owner }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Derive Docker tags from semantic-release
        if: steps.semantic.outputs.new-release-published == 'true'
        id: docker-tags
        run: |
          VERSION="${{ steps.semantic.outputs.release-version }}"

          if [ -z "$VERSION" ]; then
            echo "semantic-release did not provide release-version" >&2
            exit 1
          fi

          if [[ "$VERSION" == *"-"* ]]; then
            TAGS="ghcr.io/${{ github.repository_owner }}/gitea-ai-assistant:${VERSION}"
          else
            MAJOR="${VERSION%%.*}"
            REST="${VERSION#*.}"
            MINOR="${REST%%.*}"

            TAGS=$(printf '%s\n' \
              "ghcr.io/${{ github.repository_owner }}/gitea-ai-assistant:latest" \
              "ghcr.io/${{ github.repository_owner }}/gitea-ai-assistant:${MAJOR}" \
              "ghcr.io/${{ github.repository_owner }}/gitea-ai-assistant:${MAJOR}.${MINOR}" \
              "ghcr.io/${{ github.repository_owner }}/gitea-ai-assistant:${VERSION}")
          fi

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

          echo "Release version: ${VERSION}"
          echo "Docker tags to push:"
          echo "$TAGS"

      - name: Build and push Docker image
        if: steps.semantic.outputs.new-release-published == 'true'
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: ${{ steps.docker-tags.outputs.tags }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
