# Copyright 2024 RustFS Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

name: Publish helm chart to artifacthub

on:
  workflow_run:
    workflows: [ "Build and Release" ]
    types: [ completed ]

permissions:
  contents: read

env:
  new_version: ${{ github.event.workflow_run.head_branch }}

jobs:
  build-helm-package:
    runs-on: ubicloud-standard-2
    # Only run on successful builds triggered by tag pushes (version format: x.y.z or x.y.z-suffix)
    if: |
      github.event.workflow_run.conclusion == 'success' && 
      github.event.workflow_run.event == 'push' &&
      contains(github.event.workflow_run.head_branch, '.')

    steps:
      - name: Checkout helm chart repo
        uses: actions/checkout@v6

      - name: Replace chart app version
        run: |
          set -e
          set -x
          old_version=$(grep "^appVersion:" helm/rustfs/Chart.yaml | awk '{print $2}')
          sed -i "s/$old_version/$new_version/g" helm/rustfs/Chart.yaml

      - name: Set up Helm
        uses: azure/setup-helm@v4.3.0

      - name: Package Helm Chart
        run: |
          cp helm/README.md helm/rustfs/
          package_version=$(echo $new_version | awk -F '-' '{print $2}' | awk -F '.' '{print $NF}') 
          helm package ./helm/rustfs --destination helm/rustfs/ --version "0.0.$package_version"

      - name: Upload helm package as artifact
        uses: actions/upload-artifact@v6
        with:
          name: helm-package
          path: helm/rustfs/*.tgz
          retention-days: 1

  publish-helm-package:
    runs-on: ubicloud-standard-2
    needs: [ build-helm-package ]

    steps:
      - name: Checkout helm package repo
        uses: actions/checkout@v6
        with:
          repository: rustfs/helm
          token: ${{ secrets.RUSTFS_HELM_PACKAGE }}

      - name: Download helm package
        uses: actions/download-artifact@v7
        with:
          name: helm-package
          path: ./

      - name: Set up helm
        uses: azure/setup-helm@v4.3.0

      - name: Generate index
        run: helm repo index . --url https://charts.rustfs.com

      - name: Push helm package and index file
        run: |
          git config --global user.name "${{ secrets.USERNAME }}"
          git config --global user.email "${{ secrets.EMAIL_ADDRESS }}"
          git status .
          git add .
          git commit -m "Update rustfs helm package with $new_version."
          git push origin main
