name: Gitea CI/CD

on:
  workflow_dispatch:
  push:
    branches: [ "development", "main", "staging" ]
    tags: [ "v*.*.*" ]

env:
  DOTNET_VERSION: '8.0.x'
  DOCKER_IMAGE_NAME: watcher-server
  REGISTRY_URL: git.triggermeelmo.com
  DOCKER_PLATFORMS: 'linux/amd64'

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  dotnet-build-and-test:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          submodules: false

      # NuGet Cache
      - name: Cache NuGet packages
        uses: actions/cache@v3
        with:
          path: ~/.nuget/packages
          key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj') }}
          restore-keys: |
            ${{ runner.os }}-nuget-

      - name: Setup .NET SDK
        uses: actions/setup-dotnet@v3
        with:
          dotnet-version: ${{ env.DOTNET_VERSION }}

      - name: Restore dependencies
        run: dotnet restore watcher-monitoring.sln

      - name: Build
        run: dotnet build watcher-monitoring.sln --configuration Release --no-restore

      - name: Test
        run: dotnet test watcher-monitoring.sln --no-build --verbosity normal
        continue-on-error: true

  set-tag:
    name: Set Tag Name
    needs: [dotnet-build-and-test]
    runs-on: ubuntu-latest
    outputs:
      tag_name: ${{ steps.set_tag.outputs.tag_name }}
      should_tag: ${{ steps.set_tag.outputs.should_tag }}
    steps:
      - uses: actions/checkout@v4

      - name: Determine next semantic version tag
        id: set_tag
        run: |
          git fetch --tags

          # Find latest tag matching vX.Y.Z
          latest_tag=$(git tag --list 'v*.*.*' --sort=-v:refname | head -n 1)
          if [[ -z "$latest_tag" ]]; then
            major=0
            minor=0
            patch=0
          else
            version="${latest_tag#v}"
            IFS='.' read -r major minor patch <<< "$version"
          fi

          if [[ "${GITHUB_REF}" == "refs/heads/main" ]]; then
            major=$((major + 1))
            minor=0
            patch=0
            new_tag="v${major}.${minor}.${patch}"
            echo "tag_name=${new_tag}" >> $GITHUB_OUTPUT
            echo "should_tag=true" >> $GITHUB_OUTPUT
            echo "Creating new major version tag: ${new_tag}"
            
          elif [[ "${GITHUB_REF}" == "refs/heads/development" ]]; then
            minor=$((minor + 1))
            patch=0
            new_tag="v${major}.${minor}.${patch}"
            echo "tag_name=${new_tag}" >> $GITHUB_OUTPUT
            echo "should_tag=true" >> $GITHUB_OUTPUT
            echo "Creating new minor version tag: ${new_tag}"
            
          elif [[ "${GITHUB_REF}" == "refs/heads/staging" ]]; then
            patch=$((patch + 1))
            new_tag="v${major}.${minor}.${patch}"
            echo "tag_name=${new_tag}" >> $GITHUB_OUTPUT
            echo "should_tag=true" >> $GITHUB_OUTPUT
            echo "Creating new patch version tag: ${new_tag}"
          fi

  docker-build-and-push:
    runs-on: ubuntu-latest
    needs: [dotnet-build-and-test, set-tag]
    if: | 
      needs.set-tag.outputs.should_tag == 'true' &&
      github.event_name != 'pull_request'
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Docker Buildx
        uses: docker/setup-buildx-action@v2

      # Docker Layer Cache
      - name: Cache Docker layers
        uses: actions/cache@v3
        with:
          path: /tmp/.buildx-cache
          key: ${{ runner.os }}-buildx-${{ github.sha }}
          restore-keys: |
            ${{ runner.os }}-buildx-

      - name: Login to Gitea Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY_URL}}
          username: ${{ secrets.AUTOMATION_USERNAME }}
          password: ${{ secrets.AUTOMATION_PASSWORD }}

      - name: Build and Push Docker Image
        uses: docker/build-push-action@v5
        with:
          context: .
          platforms: ${{ env.DOCKER_PLATFORMS }}
          push: true
          tags: ${{ env.REGISTRY_URL }}/triggermeelmo/${{ env.DOCKER_IMAGE_NAME }}:${{ needs.set-tag.outputs.tag_name }}
          build-args: |
            VERSION=${{ needs.set-tag.outputs.tag_name }}
          cache-from: type=local,src=/tmp/.buildx-cache
          cache-to: type=local,dest=/tmp/.buildx-cache-new,mode=max

      # Workaround für Cache-Größe
      - name: Move cache
        run: |
          rm -rf /tmp/.buildx-cache
          mv /tmp/.buildx-cache-new /tmp/.buildx-cache

  tag:
    name: Create Tag
    needs: [docker-build-and-push, set-tag]
    if: |
      needs.set-tag.outputs.should_tag == 'true' &&
      github.event_name != 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Set up Git user
        run: |
          git config user.name "GitHub Actions"
          git config user.email "actions@github.com"

      - name: Create and push tag
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          echo "Creating new tag: ${{ needs.set-tag.outputs.tag_name }}"
          git tag ${{ needs.set-tag.outputs.tag_name }}
          git push origin ${{ needs.set-tag.outputs.tag_name }}