name: Build and Push Helm Chart

on:
  push:
    branches:
      - main
    tags:
      - 'v*.*.*'

jobs:
  build-and-push:
    name: Build image & push
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      # Step 1: Check out the repository
      - name: Checkout code
        uses: actions/checkout@v3

      # Step 2: Extract version from __version__.py
      - name: Extract version
        run: |
          VERSION=$(python -c "exec(open('__version__.py').read()); print(__version__)")
          echo "Version is $VERSION"
          echo "VERSION=$VERSION" >> $GITHUB_ENV

      # Step 3: Set up Helm
      - name: Set up Helm
        uses: azure/setup-helm@v3
        with:
          version: v3.12.0

      # Step 4: Authenticate to GitHub Container Registry
      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v2
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      # Step 5: Package the Helm Chart
      - name: Package Helm Chart
        run: |
          helm package helm/openspoolman --version=${{ env.VERSION }} --app-version=${{ env.VERSION }} --destination ./

      # Step 6: Push the Helm Chart to GHCR
      - name: Push Helm Chart to GHCR
        run: |
          CHART_NAME=$(helm show chart helm/openspoolman | grep '^name:' | awk '{print $2}')
          CHART_VERSION=${{ env.VERSION }}
          CHART_FILE="${CHART_NAME}-${CHART_VERSION}.tgz"
          echo "Pushing chart: $CHART_FILE"

          # Push chart to GHCR
          helm push "$CHART_FILE" oci://ghcr.io/${{ github.repository }}/helm
