name: Release Helm chart
on:
  push:
    branches: [main]
env:
  CR_CONFIGFILE: "${{ github.workspace }}/source/operations/helm/cr.yaml"
  CT_CONFIGFILE: "${{ github.workspace }}/source/operations/helm/ct.yaml"
  CR_INDEX_PATH: "${{ github.workspace }}/.cr-index"
  CR_PACKAGE_PATH: "${{ github.workspace }}/.cr-release-packages"
  CR_TOOL_PATH: "${{ github.workspace }}/.cr-tool"
jobs:
  setup:
    runs-on: ubuntu-latest
    outputs:
      changed: ${{ steps.list-changed.outputs.changed }}
      chartpath: ${{ steps.list-changed.outputs.chartpath }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          path: source

      - name: Install chart-testing
        uses: helm/chart-testing-action@v2.6.1

      - name: List changed charts
        id: list-changed
        run: |
          cd source

          latest_tag=$( if ! git describe --tags --abbrev=0 --match='helm-chart/*' 2> /dev/null ; then git rev-list --max-parents=0 --first-parent HEAD; fi )

          echo "Running: ct list-changed --config ${CT_CONFIGFILE} --since ${latest_tag} --target-branch ${{ github.ref_name }}"
          changed=$(ct list-changed --config "${CT_CONFIGFILE}" --since "${latest_tag}" --target-branch "${{ github.ref_name }}")
          echo "${changed}"

          num_changed=$(wc -l <<< ${changed})
          if [[ "${num_changed}" -gt "1" ]] ; then
            echo "More than one chart changed, exiting"
            exit 1
          fi
          if [[ -n "${changed}" ]]; then
            name=$(yq ".name" < ${changed}/Chart.yaml)
            version=$(yq ".version" < ${changed}/Chart.yaml)

            if [ $(git tag -l "helm-chart/${version}") ]; then
              echo "Tag helm-chart/${tagname} already exists, skipping release"
              echo "changed=false" >> $GITHUB_OUTPUT
            else
              echo "Releasing ${changed}"
              echo "changed=true" >> $GITHUB_OUTPUT
              echo "chartpath=${changed}" >> $GITHUB_OUTPUT
            fi
          else
            echo "No charts have changed, skipping release"
            echo "changed=false" >> $GITHUB_OUTPUT
          fi

  release:
    needs: [setup]
    runs-on: ubuntu-latest
    if: needs.setup.outputs.changed == 'true'
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          path: source

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

      - name: Checkout helm-charts
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          repository: grafana/helm-charts
          path: helm-charts
          token: "${{ secrets.GH_BOT_ACCESS_TOKEN }}"

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

      - name: Set up Helm
        uses: azure/setup-helm@v4
        with:
          version: v3.10.3

      - name: Parse Chart.yaml
        id: parse-chart
        run: |
          cd source
          changed="${{ needs.setup.outputs.chartpath }}"
          description=$(yq ".description" < ${changed}/Chart.yaml)
          name=$(yq ".name" < ${changed}/Chart.yaml)
          version=$(yq ".version" < ${changed}/Chart.yaml)
          echo "chartpath=${changed}" >> $GITHUB_OUTPUT
          echo "desc=${description}" >> $GITHUB_OUTPUT
          echo "tagname=helm-chart/${version}" >> $GITHUB_OUTPUT
          echo "packagename=${name}-${version}" >> $GITHUB_OUTPUT

      - name: Install CR tool
        run: |
          mkdir "${CR_TOOL_PATH}"
          mkdir "${CR_PACKAGE_PATH}"
          mkdir "${CR_INDEX_PATH}"
          curl -sSLo cr.tar.gz "https://github.com/helm/chart-releaser/releases/download/v1.5.0/chart-releaser_1.5.0_linux_amd64.tar.gz"
          tar -xzf cr.tar.gz -C "${CR_TOOL_PATH}"
          rm -f cr.tar.gz

      - name: Create Helm package
        run: |
          cd source
          "${CR_TOOL_PATH}/cr" package "${{ steps.parse-chart.outputs.chartpath }}" --config "${CR_CONFIGFILE}" --package-path "${CR_PACKAGE_PATH}"
          echo "Result of chart package:"
          ls -l "${CR_PACKAGE_PATH}"

      - name: Create tag and check if exists on origin
        run: |
          cd source
          echo "Making tag ${{ steps.parse-chart.outputs.tagname }}"
          git tag "${{ steps.parse-chart.outputs.tagname }}"

      # Note that this creates a release in grafana/helm-charts with a new tag.
      # The tag name in grafana/helm-charts is <package>-<version>, while the
      # tag name for grafana/agent is helm-chart/<version>.
      - name: Make github release
        uses: softprops/action-gh-release@v2
        with:
          name: ${{ steps.parse-chart.outputs.packagename }}
          repository: grafana/helm-charts
          tag_name: ${{ steps.parse-chart.outputs.packagename }}
          token: ${{ secrets.GH_BOT_ACCESS_TOKEN }}
          body: |
            ${{ steps.parse-chart.outputs.desc }}

            Source commit: https://github.com/${{ github.repository }}/commit/${{ github.sha }}

            Tag on source: https://github.com/${{ github.repository }}/releases/tag/${{ steps.parse-chart.outputs.tagname }}
          files: |
            ${{ env.CR_PACKAGE_PATH }}/${{ steps.parse-chart.outputs.packagename }}.tgz

      - name: Push release tag on origin
        run: |
          cd source
          echo "Pushing tag ${{ steps.parse-chart.outputs.tagname }}"
          git push origin "${{ steps.parse-chart.outputs.tagname }}"

      - name: Update helm-charts index.yaml
        run: |
          cd helm-charts
          "${CR_TOOL_PATH}/cr" index --config "${CR_CONFIGFILE}" --token "${{ secrets.GH_BOT_ACCESS_TOKEN }}" --index-path "${CR_INDEX_PATH}" --package-path "${CR_PACKAGE_PATH}" --push