name: Build and Push Docker Image only on Conventional Commits

on:
  push:
    branches:
      - '**'

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      DOCKER_REGISTRY: git.trai-infra.comstack.de
      DOCKER_IMAGE: marian.lippitz/tap-frontend

    steps:
      - name: Checkout Code
        uses: actions/checkout@v4
        with:
          fetch-depth: 1

      - name: Validate Conventional Commit (subject line only)
        id: validate
        run: |
          SUBJECT="$(git log -1 --pretty=%s)"
          echo "Commit subject: $SUBJECT"
          if echo "$SUBJECT" | grep -Eq '^(feat|fix|docs|style|refactor|perf|test|chore|build|ci|revert)(\(.+\))?: .+'; then
            echo "valid=true" >> "$GITHUB_OUTPUT"
          else
            echo "valid=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Stop if not a Conventional Commit
        if: ${{ steps.validate.outputs.valid != 'true' }}
        run: |
          echo "Latest commit is not a valid Conventional Commit. Skipping build."
          exit 0

      - name: Log in to registry
        if: ${{ steps.validate.outputs.valid == 'true' }}
        uses: docker/login-action@v3
        with:
          registry: ${{ env.DOCKER_REGISTRY }}
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      - name: Set up Docker Buildx
        if: ${{ steps.validate.outputs.valid == 'true' }}
        uses: docker/setup-buildx-action@v3

      - name: Determine Docker tag
        id: docker_tag
        if: ${{ steps.validate.outputs.valid == 'true' }}
        run: |
          if [ "${{ github.ref_name }}" == "main" ]; then
            echo "tag=latest" >> "$GITHUB_OUTPUT"
          else
            echo "tag=dev" >> "$GITHUB_OUTPUT"
          fi

      - name: Build and push
        if: ${{ steps.validate.outputs.valid == 'true' }}
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ${{ env.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:${{ steps.docker_tag.outputs.tag }}
          provenance: false  # avoids warnings on some registries

      - name: Install kubectl
        if: ${{ steps.validate.outputs.valid == 'true' }}      
        uses: azure/setup-kubectl@v4
        with:
          version: v1.34.1

      - name: Write kubeconfig
        if: ${{ steps.validate.outputs.valid == 'true' }}      
        run: |
          umask 077
          echo "${{ secrets.KUBECONFIG }}" > kubeconfig

      - name: Restart deployment and wait
        if: ${{ steps.validate.outputs.valid == 'true' && github.ref_name == 'main' }}
        env:
          KUBECONFIG: ${{ github.workspace }}/kubeconfig
        run: |
          set -euo pipefail
          kubectl -n frontend rollout restart deployment/tap-frontend
          kubectl -n frontend rollout status deployment/tap-frontend --timeout=180s