name: Build / Deploy Helm Chart

on:
  workflow_dispatch:

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Set up Helm
        uses: azure/setup-helm@v4.3.1
        with:
          version: 'latest'

      - name: Update Helm chart dependencies
        run: |
          cd ./helm/opengist
          helm dependency update

      - name: Package Helm chart
        run: |
          cd ./helm
          helm package ./opengist

          # First time, create the index
          wget -q https://helm.opengist.io/index.yaml
          if [ ! -f index.yaml ]; then
            helm repo index --url https://helm.opengist.io .
          else
            # For subsequent runs, merge with existing index
            helm repo index --url https://helm.opengist.io --merge index.yaml .
          fi

      - name: Push to docs repository
        run: |
          git clone https://${{ secrets.STATIC_REPO_TOKEN }}@github.com/${{ secrets.STATIC_REPO }}.git target-repo
          mkdir -p target-repo/helm
          cp helm/*.tgz target-repo/srv/helm/
          cp helm/index.yaml target-repo/srv/helm/
          cd target-repo
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add .
          git commit -m "Deploy helm chart from ${{ github.repository }}@${{ github.sha }}" || echo "No changes to commit"
          git pull --rebase
          git push
