name: Push

on:
  push:
    branches:
      - master
    paths:
      - '**'
      - '!.markdownlint.yaml'
      - '!.vale.ini'
      - '!Dockerfile-docs'
      - '!docs-nginx.conf'
      - '!docs/**'
      - '!theme_common'
      - '!theme_override'

env:
  DOCKER_FILE_PATH: Dockerfile
  DOCKER_UBI_FILE_PATH: Dockerfile.ubi
  KUBERNETES_VERSION: "1.19.0"
  KIND_VERSION: "0.17.0"
  HELM_REGISTRY_URL: "https://stakater.github.io/stakater-charts"
  REGISTRY: ghcr.io

jobs:
  build:
    name: Build
    if: "! contains(toJSON(github.event.commits.*.message), '[skip-ci]')"
    runs-on: ubuntu-latest

    steps:
      - name: Check out code
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.STAKATER_GITHUB_TOKEN }}
          fetch-depth: 0 # otherwise, you will fail to push refs to dest repo

      # Setting up helm binary
      - name: Set up Helm
        uses: azure/setup-helm@v4
        with:
          version: v3.11.3

      - name: Set up Go
        uses: actions/setup-go@v5
        with:
          go-version-file: 'go.mod'
          check-latest: true
          cache: true

      - name: Install Dependencies
        run: |
          make install

      - name: Run golangci-lint
        uses: golangci/golangci-lint-action@v5
        with:
          version: latest
          only-new-issues: false
          args: --timeout 10m

      - name: Install kubectl
        run: |
          curl -LO "https://storage.googleapis.com/kubernetes-release/release/v${KUBERNETES_VERSION}/bin/linux/amd64/kubectl"
          sudo install ./kubectl /usr/local/bin/ && rm kubectl
          kubectl version --short --client
          kubectl version --short --client | grep -q ${KUBERNETES_VERSION}

      - name: Install Kind
        run: |
          curl -L -o kind https://github.com/kubernetes-sigs/kind/releases/download/v${KIND_VERSION}/kind-linux-amd64
          sudo install ./kind /usr/local/bin && rm kind
          kind version
          kind version | grep -q ${KIND_VERSION}

      - name: Create Kind Cluster
        run: |
          kind create cluster
          kubectl cluster-info

      - name: Test
        run: make test

      - name: Generate Tag
        id: generate_tag
        uses: anothrNick/github-tag-action@1.69.0
        env:
          GITHUB_TOKEN: ${{ secrets.STAKATER_GITHUB_TOKEN }}
          WITH_V: true
          DEFAULT_BUMP: patch
          DRY_RUN: true

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Login to Docker Registry
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.STAKATER_DOCKERHUB_USERNAME }}
          password: ${{ secrets.STAKATER_DOCKERHUB_PASSWORD }}

      - name: Generate image repository path for Docker registry
        run: |
          echo DOCKER_IMAGE_REPOSITORY=$(echo ${{ github.repository }} | tr '[:upper:]' '[:lower:]') >> $GITHUB_ENV

      - name: Build and Push Docker Image to Docker registry
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ${{ env.DOCKER_FILE_PATH  }}
          pull: true
          push: true
          build-args: BUILD_PARAMETERS=${{ env.BUILD_PARAMETERS }}
          cache-to: type=inline
          platforms: linux/amd64,linux/arm,linux/arm64
          tags: |
            ${{ env.DOCKER_IMAGE_REPOSITORY }}:${{ steps.generate_tag.outputs.new_tag }}
          labels: |
            org.opencontainers.image.source=${{ github.event.repository.clone_url }}
            org.opencontainers.image.created=${{ steps.prep.outputs.created }}
            org.opencontainers.image.revision=${{ github.sha }}

      - name: Build and Push Docker UBI Image to Docker registry
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ${{ env.DOCKER_UBI_FILE_PATH  }}
          pull: true
          push: true
          build-args: |
            BUILD_PARAMETERS=${{ env.BUILD_PARAMETERS }}
            BUILDER_IMAGE=${{ env.DOCKER_IMAGE_REPOSITORY }}:${{ steps.generate_tag.outputs.new_tag }}
          cache-to: type=inline
          platforms: linux/amd64,linux/arm64
          tags: |
            ${{ env.DOCKER_IMAGE_REPOSITORY }}:${{ steps.generate_tag.outputs.new_tag }}-ubi
          labels: |
            org.opencontainers.image.source=${{ github.event.repository.clone_url }}
            org.opencontainers.image.created=${{ steps.prep.outputs.created }}
            org.opencontainers.image.revision=${{ github.sha }}

      - name: Login to ghcr registry
        uses: docker/login-action@v3
        with:
          registry: ${{env.REGISTRY}}
          username: stakater-user
          password: ${{secrets.GITHUB_TOKEN}}

      - name: Generate image repository path for ghcr registry
        run: |
          echo GHCR_IMAGE_REPOSITORY=${{env.REGISTRY}}/$(echo ${{ github.repository }} | tr '[:upper:]' '[:lower:]') >> $GITHUB_ENV

      - name: Build and Push Docker Image to ghcr registry
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ${{ env.DOCKER_FILE_PATH  }}
          pull: true
          push: true
          build-args: BUILD_PARAMETERS=${{ env.BUILD_PARAMETERS }}
          cache-to: type=inline
          platforms: linux/amd64,linux/arm,linux/arm64
          tags: |
            ${{ env.GHCR_IMAGE_REPOSITORY }}:${{ steps.generate_tag.outputs.new_tag }}
          labels: |
            org.opencontainers.image.source=${{ github.event.repository.clone_url }}
            org.opencontainers.image.created=${{ steps.prep.outputs.created }}
            org.opencontainers.image.revision=${{ github.sha }}

      - name: Build and Push Docker UBI Image to ghcr registry
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ${{ env.DOCKER_UBI_FILE_PATH  }}
          pull: true
          push: true
          build-args: |
            BUILD_PARAMETERS=${{ env.BUILD_PARAMETERS }}
            BUILDER_IMAGE=${{ env.GHCR_IMAGE_REPOSITORY }}:${{ steps.generate_tag.outputs.new_tag }}
          cache-to: type=inline
          platforms: linux/amd64,linux/arm64
          tags: |
            ${{ env.GHCR_IMAGE_REPOSITORY }}:${{ steps.generate_tag.outputs.new_tag }}-ubi
          labels: |
            org.opencontainers.image.source=${{ github.event.repository.clone_url }}
            org.opencontainers.image.created=${{ steps.prep.outputs.created }}
            org.opencontainers.image.revision=${{ github.sha }}

      ##############################
      ## Add steps to generate required artifacts for a release here(helm chart, operator manifest etc.)
      ##############################

      # Generate tag for operator without "v"
      - name: Generate Operator Tag
        id: generate_operator_tag
        uses: anothrNick/github-tag-action@1.69.0
        env:
          GITHUB_TOKEN: ${{ secrets.STAKATER_GITHUB_TOKEN }}
          WITH_V: false
          DEFAULT_BUMP: patch
          DRY_RUN: true

      # Update chart tag to the latest semver tag
      - name: Update Chart Version
        env:
          VERSION: ${{ steps.generate_operator_tag.outputs.new_tag }}
        run: make bump-chart

      - name: Helm Template
        run: |
          helm template reloader deployments/kubernetes/chart/reloader/ > deployments/kubernetes/reloader.yaml
          helm template reloader deployments/kubernetes/chart/reloader/ --output-dir deployments/kubernetes/manifests && mv deployments/kubernetes/manifests/reloader/templates/* deployments/kubernetes/manifests/ && rm -r deployments/kubernetes/manifests/reloader

      - name: Remove labels and annotations from manifests
        run: make remove-labels-annotations

      # Publish helm chart
      - name: Login to ghcr via helm
        run: |
          echo ${{secrets.GITHUB_TOKEN}} | helm registry login ghcr.io/stakater --username stakater-user --password-stdin

      - name: Publish Helm chart to ghcr.io
        run: |
          helm package ./deployments/kubernetes/chart/reloader --destination ./packaged-chart
          helm push ./packaged-chart/*.tgz oci://ghcr.io/stakater/charts
          rm -rf ./packaged-chart

      - name: Publish Helm chart to gh-pages
        uses: stefanprodan/helm-gh-pages@master
        with:
          branch: master
          repository: stakater-charts
          target_dir: docs
          token: ${{ secrets.STAKATER_GITHUB_TOKEN }}
          charts_dir: deployments/kubernetes/chart/
          charts_url: ${{ env.HELM_REGISTRY_URL }}
          owner: stakater
          linting: on
          commit_username: stakater-user
          commit_email: stakater@gmail.com

      # Commit back changes
      - name: Log info about `.git` directory permissions
        run: |
          # Debug logging
          echo "Disk usage: "
          df -H

          echo ".git files not owned by current user or current group:"
          find .git ! -user $(id -u) -o ! -group $(id -g) | xargs ls -lah

      - name: Commit files
        run: |
          git config --local user.email "stakater@gmail.com"
          git config --local user.name "stakater-user"
          git status
          git add .
          git commit -m "[skip-ci] Update artifacts" -a

      - name: Push changes
        uses: ad-m/github-push-action@master
        with:
          github_token: ${{ secrets.STAKATER_GITHUB_TOKEN }}
          branch: ${{ github.ref }}

      - name: Push Latest Tag
        uses: anothrNick/github-tag-action@1.69.0
        env:
          GITHUB_TOKEN: ${{ secrets.STAKATER_GITHUB_TOKEN }}
          WITH_V: true
          DEFAULT_BUMP: patch

      - name: Notify Slack
        uses: 8398a7/action-slack@v3
        if: always() # Pick up events even if the job fails or is canceled.
        with:
          status: ${{ job.status }}
          fields: repo,author,action,eventName,ref,workflow
        env:
          GITHUB_TOKEN: ${{ secrets.STAKATER_GITHUB_TOKEN }}
          SLACK_WEBHOOK_URL: ${{ secrets.STAKATER_DELIVERY_SLACK_WEBHOOK }}
