name: Hosting - Publish Helm chart to static.colanode.com

on:
  push:
    branches: [main]
    paths:
      - 'hosting/kubernetes/chart/**'
      - '.github/workflows/helm-chart-publish.yml'
  workflow_dispatch:

jobs:
  publish:
    runs-on: ubuntu-latest
    env:
      S3_ACCESS_KEY_ID: ${{ secrets.S3_ACCESS_KEY_ID }}
      S3_SECRET_ACCESS_KEY: ${{ secrets.S3_SECRET_ACCESS_KEY }}
      S3_ENDPOINT: ${{ secrets.S3_ENDPOINT }}
      S3_BUCKET: ${{ secrets.S3_BUCKET }}
      S3_REGION: ${{ secrets.S3_REGION }}
      CHART_DIR: hosting/kubernetes/chart

    steps:
      - uses: actions/checkout@v4

      - uses: azure/setup-helm@v3
        with: { version: v3.14.3 }

      - run: helm dependency update "$CHART_DIR"

      - name: Configure AWS CLI
        run: aws configure set default.s3.addressing_style path

      - name: Package chart
        run: |
          mkdir -p dist
          helm package "$CHART_DIR" --destination dist

      - name: Fetch existing index.yaml
        run: |
          aws s3 cp s3://${{ secrets.S3_BUCKET }}/hosting/kubernetes/chart/index.yaml dist/index.yaml \
            --endpoint-url "$S3_ENDPOINT" --region "$S3_REGION" --checksum-algorithm CRC32 || true

      - name: Re-index repo
        working-directory: dist
        run: |
          helm repo index . \
            --url "https://static.colanode.com/hosting/kubernetes/chart" \
            $(test -f index.yaml && echo "--merge index.yaml")

      - name: Upload chart and index to S3
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.S3_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.S3_SECRET_ACCESS_KEY }}
          AWS_S3_ADDRESSING_STYLE: path
        run: |
          aws s3 cp dist/ s3://${{ secrets.S3_BUCKET }}/hosting/kubernetes/chart/ \
            --recursive \
            --endpoint-url "$S3_ENDPOINT" \
            --region "$S3_REGION" \
            --checksum-algorithm CRC32
