name: Helm Chart CI/CD

on:
  push:
    branches: [ main ]
    paths:
      - 'charts/**'
      - '.github/workflows/helm-chart-ci-cd.yaml'
  pull_request:
    branches: [ main ]
    paths:
      - 'charts/**'
      - '.github/workflows/helm-chart-ci-cd.yaml'
  release:
    types: [created]

env:
  CHART_NAME: postiz
  CHART_PATH: ./charts/postiz

jobs:
  lint-test:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

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

      - name: Install Chart deps
        run: |
          helm repo add bitnami https://charts.bitnami.com/bitnami

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.x'
          check-latest: false

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

      - name: Run chart-testing (list-changed)
        id: list-changed
        run: |
          changed=$(ct list-changed --config ct.yaml --target-branch ${{ github.event.repository.default_branch }})
          if [[ -n "$changed" ]]; then
            echo "changed=true" >> $GITHUB_OUTPUT
          fi

      - name: Run chart-testing (lint)
        run: ct lint --config ct.yaml --target-branch ${{ github.event.repository.default_branch }}

      - name: Create kind cluster
        uses: helm/kind-action@v1.10.0
        if: steps.list-changed.outputs.changed == 'true'

      - name: Run chart-testing (install)
        run: ct install --config ct.yaml --target-branch ${{ github.event.repository.default_branch }}

  publish:
    needs: lint-test
    runs-on: ubuntu-latest
    if: github.event_name == 'release'
    steps:
      - name: Checkout
        uses: actions/checkout@v4

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

      - name: Add dependency repositories
        run: |
          helm repo add bitnami https://charts.bitnami.com/bitnami

      - name: Update dependencies
        run: |
          helm dependency update ${{ env.CHART_PATH }}

      - name: Package Helm chart
        run: |
          helm package ${{ env.CHART_PATH }}

      - name: Run chart-releaser
        uses: helm/chart-releaser-action@v1.6.0
        env:
          CR_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
        with:
          charts_dir: charts

      - name: Login to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Push Helm chart to GitHub Packages
        run: |
          helm push ${{ env.CHART_NAME }}*.tgz oci://ghcr.io/${{ github.repository }}/charts
