name: Publish ARC Helm Charts

# Revert to https://github.com/actions-runner-controller/releases#releases
# for details on why we use this approach
on:
  push:
    branches:
    - master
    paths:
    - 'charts/**'
    - '.github/workflows/arc-publish-chart.yaml'
    - '!charts/actions-runner-controller/docs/**'
    - '!charts/gha-runner-scale-set-controller/**'
    - '!charts/gha-runner-scale-set/**'
    - '!**.md'
  workflow_dispatch:
    inputs:
      force:
        description: 'Force publish even if the chart version is not bumped'
        type: boolean
        required: true
        default: false

env:
  KUBE_SCORE_VERSION: 1.10.0
  HELM_VERSION: v3.8.0

permissions:
  contents: write

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

jobs:
  lint-chart:
    name: Lint Chart
    runs-on: ubuntu-latest
    outputs:
      publish-chart: ${{ steps.publish-chart-step.outputs.publish }}
    steps:
    - name: Checkout
      uses: actions/checkout@v4
      with:
        fetch-depth: 0

    - name: Set up Helm
      uses: azure/setup-helm@fe7b79cd5ee1e45176fcad797de68ecaf3ca4814
      with:
        version: ${{ env.HELM_VERSION }}

    - name: Set up kube-score
      run: |
        wget https://github.com/zegl/kube-score/releases/download/v${{ env.KUBE_SCORE_VERSION }}/kube-score_${{ env.KUBE_SCORE_VERSION }}_linux_amd64 -O kube-score
        chmod 755 kube-score

    - name: Kube-score generated manifests
      run: helm template  --values charts/.ci/values-kube-score.yaml charts/* | ./kube-score score - --ignore-test pod-networkpolicy --ignore-test deployment-has-poddisruptionbudget --ignore-test deployment-has-host-podantiaffinity --ignore-test container-security-context --ignore-test pod-probes --ignore-test container-image-tag --enable-optional-test container-security-context-privileged --enable-optional-test container-security-context-readonlyrootfilesystem

    # python is a requirement for the chart-testing action below (supports yamllint among other tests)
    - uses: actions/setup-python@v5
      with:
        python-version: '3.11'

    - name: Set up chart-testing
      uses: helm/chart-testing-action@v2.6.0

    - name: Run chart-testing (list-changed)
      id: list-changed
      run: |
        changed=$(ct list-changed --config charts/.ci/ct-config.yaml)
        if [[ -n "$changed" ]]; then
          echo "changed=true" >> $GITHUB_OUTPUT
        fi

    - name: Run chart-testing (lint)
      run: |
        ct lint --config charts/.ci/ct-config.yaml

    - name: Create kind cluster
      if: steps.list-changed.outputs.changed == 'true'
      uses: helm/kind-action@v1.4.0

    # We need cert-manager already installed in the cluster because we assume the CRDs exist
    - name: Install cert-manager
      if: steps.list-changed.outputs.changed == 'true'
      run: |
        helm repo add jetstack https://charts.jetstack.io --force-update
        helm install cert-manager jetstack/cert-manager --set installCRDs=true --wait

    - name: Run chart-testing (install)
      if: steps.list-changed.outputs.changed == 'true'
      run: ct install --config charts/.ci/ct-config.yaml

    # WARNING: This relies on the latest release being at the top of the JSON from GitHub and a clean chart.yaml
    - name: Check if Chart Publish is Needed
      id: publish-chart-step
      run: |
        CHART_TEXT=$(curl -fs https://raw.githubusercontent.com/${{ github.repository }}/master/charts/actions-runner-controller/Chart.yaml)
        NEW_CHART_VERSION=$(echo "$CHART_TEXT" | grep version: | cut -d ' ' -f 2)
        RELEASE_LIST=$(curl -fs https://api.github.com/repos/${{ github.repository }}/releases  | jq .[].tag_name | grep actions-runner-controller | cut -d '"' -f 2 | cut -d '-' -f 4)
        LATEST_RELEASED_CHART_VERSION=$(echo $RELEASE_LIST | cut -d ' ' -f 1)

        echo "CHART_VERSION_IN_MASTER=$NEW_CHART_VERSION" >> $GITHUB_ENV
        echo "LATEST_CHART_VERSION=$LATEST_RELEASED_CHART_VERSION" >> $GITHUB_ENV

        # Always publish if force is true
        if [[ $NEW_CHART_VERSION != $LATEST_RELEASED_CHART_VERSION || "${{ inputs.force }}" == "true" ]]; then
          echo "publish=true" >> $GITHUB_OUTPUT
        else
          echo "publish=false" >> $GITHUB_OUTPUT
        fi

    - name: Job summary
      run: |
        echo "Chart linting has been completed." >> $GITHUB_STEP_SUMMARY
        echo "" >> $GITHUB_STEP_SUMMARY
        echo "**Status:**" >> $GITHUB_STEP_SUMMARY
        echo "- chart version in master: ${{ env.CHART_VERSION_IN_MASTER }}" >> $GITHUB_STEP_SUMMARY
        echo "- latest chart version: ${{ env.LATEST_CHART_VERSION }}" >> $GITHUB_STEP_SUMMARY
        echo "- publish new chart: ${{ steps.publish-chart-step.outputs.publish }}" >> $GITHUB_STEP_SUMMARY

  publish-chart:
    if: needs.lint-chart.outputs.publish-chart == 'true'
    needs: lint-chart
    name: Publish Chart
    runs-on: ubuntu-latest
    permissions:
      contents: write # for helm/chart-releaser-action to push chart release and create a release
    env:
      CHART_TARGET_ORG: actions-runner-controller
      CHART_TARGET_REPO: actions-runner-controller.github.io
      CHART_TARGET_BRANCH: master

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

    - name: Configure Git
      run: |
        git config user.name "$GITHUB_ACTOR"
        git config user.email "$GITHUB_ACTOR@users.noreply.github.com"

    - name: Get Token
      id: get_workflow_token
      uses: peter-murray/workflow-application-token-action@dc0413987a085fa17d19df9e47d4677cf81ffef3
      with:
        application_id: ${{ secrets.ACTIONS_ACCESS_APP_ID }}
        application_private_key: ${{ secrets.ACTIONS_ACCESS_PK }}
        organization: ${{ env.CHART_TARGET_ORG }}

    - name: Install chart-releaser
      uses: helm/chart-releaser-action@v1.4.1
      with:
        install_only: true
        install_dir: ${{ github.workspace }}/bin

    - name: Package and upload release assets
      run: |
        cr package \
          ${{ github.workspace }}/charts/actions-runner-controller/ \
          --package-path .cr-release-packages

        cr upload \
          --owner "$(echo ${{ github.repository }} | cut -d '/' -f 1)" \
          --git-repo "$(echo ${{ github.repository }} | cut -d '/' -f 2)" \
          --package-path .cr-release-packages \
          --token ${{ secrets.GITHUB_TOKEN }}

    - name: Generate updated index.yaml
      run: |
        cr index \
          --owner "$(echo ${{ github.repository }} | cut -d '/' -f 1)" \
          --git-repo "$(echo ${{ github.repository }} | cut -d '/' -f 2)" \
          --index-path ${{ github.workspace }}/index.yaml \
          --token ${{ secrets.GITHUB_TOKEN }} \
          --push \
          --pages-branch 'gh-pages' \
          --pages-index-path 'index.yaml'

    # Chart Release was never intended to publish to a different repo
    # this workaround is intended to move the index.yaml to the target repo
    # where the github pages are hosted
    - name: Checkout target repository
      uses: actions/checkout@v4
      with:
        repository: ${{ env.CHART_TARGET_ORG }}/${{ env.CHART_TARGET_REPO }}
        path: ${{ env.CHART_TARGET_REPO }}
        ref: ${{ env.CHART_TARGET_BRANCH }}
        token: ${{ steps.get_workflow_token.outputs.token }}

    - name: Copy index.yaml
      run: |
        cp ${{ github.workspace }}/index.yaml ${{ env.CHART_TARGET_REPO }}/actions-runner-controller/index.yaml

    - name: Commit and push to target repository
      run: |
        git config user.name "$GITHUB_ACTOR"
        git config user.email "$GITHUB_ACTOR@users.noreply.github.com"
        git add .
        git commit -m "Update index.yaml"
        git push
      working-directory: ${{ github.workspace }}/${{ env.CHART_TARGET_REPO }}

    - name: Job summary
      run: |
        echo "New helm chart has been published" >> $GITHUB_STEP_SUMMARY
        echo "" >> $GITHUB_STEP_SUMMARY
        echo "**Status:**" >> $GITHUB_STEP_SUMMARY
        echo "- New [index.yaml](https://github.com/${{ env.CHART_TARGET_ORG }}/${{ env.CHART_TARGET_REPO }}/tree/master/actions-runner-controller) pushed" >> $GITHUB_STEP_SUMMARY
