name: Release Helm Chart

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

permissions:
  contents: write

concurrency:
  group: "pages"
  cancel-in-progress: false

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.17.0

      - uses: actions/setup-python@v5.3.0
        with:
          python-version: '3.x'
          check-latest: true

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

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

      - name: Run chart-testing (lint)
        if: steps.list-changed.outputs.changed == 'true'
        run: ct lint --target-branch ${{ github.event.repository.default_branch }}

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

      - name: Run chart-testing (install)
        run: |
          # Install with test values
          ct install --target-branch ${{ github.event.repository.default_branch }} --chart-dirs helm \
            --helm-extra-set-args "--set config.webauthn.rpId=test.local --set config.auth.allowedEmails={test@example.com} --set secrets.sessionSecret=test-secret-for-ci-only --set ingress.enabled=false"

  release:
    needs: lint-test
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/v')
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Configure Git
        run: |
          git config user.name "$GITHUB_ACTOR"
          git config user.email "$GITHUB_ACTOR@users.noreply.github.com"

      - name: Create gh-pages branch if it doesn't exist
        run: |
          if ! git ls-remote --exit-code --heads origin gh-pages; then
            echo "Creating gh-pages branch"
            git checkout --orphan gh-pages
            git reset --hard
            git commit --allow-empty -m "Initial gh-pages commit"
            git push origin gh-pages
            git checkout main
          fi

      - name: Install Helm
        uses: azure/setup-helm@v4
        with:
          version: '3.14.0'

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

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