name: 🧭 Helm Chart Prerelease

on:
  pull_request:
    types: [opened, synchronize, reopened]
    paths:
      - "hosting/k8s/helm/**"
  push:
    branches:
      - main
    paths:
      - "hosting/k8s/helm/**"
  workflow_dispatch:
    inputs:
      app_version:
        description: "Override appVersion (e.g. 'main', 'v4.4.4'). Leave empty to keep Chart.yaml value."
        required: false
        type: string
        default: ""

concurrency:
  group: helm-prerelease-${{ github.event.pull_request.number || github.ref }}
  cancel-in-progress: true

env:
  REGISTRY: ghcr.io
  CHART_NAME: trigger

jobs:
  lint-and-test:
    runs-on: warp-ubuntu-latest-x64-2x
    permissions:
      contents: read
    steps:
      - name: Checkout
        uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
        with:
          persist-credentials: false

      - name: Set up Helm
        uses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5.0.1
        with:
          version: "3.18.3"

      - name: Build dependencies
        run: helm dependency build ./hosting/k8s/helm/

      - name: Extract dependency charts
        run: |
          cd ./hosting/k8s/helm/
          for file in ./charts/*.tgz; do echo "Extracting $file"; tar -xzf "$file" -C ./charts; done

      - name: Lint Helm Chart
        run: |
          helm lint ./hosting/k8s/helm/

      - name: Render templates
        run: |
          helm template test-release ./hosting/k8s/helm/ \
            --values ./hosting/k8s/helm/values.yaml \
            --output-dir ./helm-output

      - name: Validate manifests
        uses: docker://ghcr.io/yannh/kubeconform:v0.7.0@sha256:85dbef6b4b312b99133decc9c6fc9495e9fc5f92293d4ff3b7e1b30f5611823c
        with:
          entrypoint: "/kubeconform"
          args: "-summary -output json ./helm-output"

  prerelease:
    needs: lint-and-test
    # Set the ENABLE_HELM_PRERELEASE repository variable to 'false' to turn off
    # publishing the chart to GHCR — e.g. forks/mirrors that lack write_package
    # on the owner's charts namespace. Defaults to enabled; the lint-and-test
    # job above always runs regardless.
    if: |
      vars.ENABLE_HELM_PRERELEASE != 'false' &&
      ((github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) ||
      github.event_name == 'push' ||
      github.event_name == 'workflow_dispatch')
    runs-on: warp-ubuntu-latest-x64-2x
    permissions:
      contents: read
      packages: write
      pull-requests: write
    steps:
      - name: Checkout
        uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
        with:
          persist-credentials: false

      - name: Set up Helm
        uses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5.0.1
        with:
          version: "3.18.3"

      - name: Build dependencies
        run: helm dependency build ./hosting/k8s/helm/

      - name: Extract dependency charts
        run: |
          cd ./hosting/k8s/helm/
          for file in ./charts/*.tgz; do echo "Extracting $file"; tar -xzf "$file" -C ./charts; done

      - name: Log in to Container Registry
        uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Generate prerelease version
        id: version
        run: |
          BASE_VERSION=$(grep '^version:' ./hosting/k8s/helm/Chart.yaml | awk '{print $2}')
          if [[ "${{ github.event_name }}" == "pull_request" ]]; then
            PR_NUMBER=${{ github.event.pull_request.number }}
            SHORT_SHA=$(echo "${{ github.event.pull_request.head.sha }}" | cut -c1-7)
            PRERELEASE_VERSION="${BASE_VERSION}-pr${PR_NUMBER}.${SHORT_SHA}"
          elif [[ "${{ github.event_name }}" == "push" ]]; then
            SHORT_SHA=$(echo "${GITHUB_SHA}" | cut -c1-7)
            PRERELEASE_VERSION="${BASE_VERSION}-main.${SHORT_SHA}"
          else
            SHORT_SHA=$(echo "${GITHUB_SHA}" | cut -c1-7)
            REF_SLUG=$(echo "${GITHUB_REF_NAME}" | tr '/' '-' | tr -cd 'a-zA-Z0-9-')
            if [[ -z "$REF_SLUG" ]]; then
              REF_SLUG="manual"
            fi
            PRERELEASE_VERSION="${BASE_VERSION}-${REF_SLUG}.${SHORT_SHA}"
          fi
          echo "version=$PRERELEASE_VERSION" >> "$GITHUB_OUTPUT"
          echo "Prerelease version: $PRERELEASE_VERSION"

      - name: Update Chart.yaml with prerelease version
        run: |
          sed -i "s/^version:.*/version: ${STEPS_VERSION_OUTPUTS_VERSION}/" ./hosting/k8s/helm/Chart.yaml
        env:
          STEPS_VERSION_OUTPUTS_VERSION: ${{ steps.version.outputs.version }}

      - name: Override appVersion
        if: github.event_name == 'workflow_dispatch' && inputs.app_version != ''
        env:
          APP_VERSION: ${{ inputs.app_version }}
        run: |
          yq -i '.appVersion = strenv(APP_VERSION)' ./hosting/k8s/helm/Chart.yaml

      - name: Package Helm Chart
        run: |
          helm package ./hosting/k8s/helm/ --destination /tmp/

      - name: Push Helm Chart to GHCR
        run: |
          VERSION="${STEPS_VERSION_OUTPUTS_VERSION}"
          CHART_PACKAGE="/tmp/${{ env.CHART_NAME }}-${VERSION}.tgz"

          # Push to GHCR OCI registry
          helm push "$CHART_PACKAGE" "oci://${{ env.REGISTRY }}/${{ github.repository_owner }}/charts"
        env:
          STEPS_VERSION_OUTPUTS_VERSION: ${{ steps.version.outputs.version }}

      - name: Write run summary
        run: |
          {
            echo "### 🧭 Helm Chart Prerelease Published"
            echo ""
            echo "**Version:** \`${STEPS_VERSION_OUTPUTS_VERSION}\`"
            echo ""
            echo "**Install:**"
            echo '```bash'
            echo "helm upgrade --install trigger \\"
            echo "  oci://${{ env.REGISTRY }}/${{ github.repository_owner }}/charts/${{ env.CHART_NAME }} \\"
            echo "  --version \"${STEPS_VERSION_OUTPUTS_VERSION}\""
            echo '```'
          } >> "$GITHUB_STEP_SUMMARY"
        env:
          STEPS_VERSION_OUTPUTS_VERSION: ${{ steps.version.outputs.version }}

      - name: Find existing comment
        if: github.event_name == 'pull_request'
        uses: peter-evans/find-comment@b30e6a3c0ed37e7c023ccd3f1db5c6c0b0c23aad # v4.0.0
        id: find-comment
        with:
          issue-number: ${{ github.event.pull_request.number }}
          comment-author: "github-actions[bot]"
          body-includes: "Helm Chart Prerelease Published"

      - name: Create or update PR comment
        if: github.event_name == 'pull_request'
        uses: peter-evans/create-or-update-comment@e8674b075228eee787fea43ef493e45ece1004c9 # v5.0.0
        with:
          comment-id: ${{ steps.find-comment.outputs.comment-id }}
          issue-number: ${{ github.event.pull_request.number }}
          body: |
            ### 🧭 Helm Chart Prerelease Published

            **Version:** `${{ steps.version.outputs.version }}`

            **Install:**
            ```bash
            helm upgrade --install trigger \
              oci://ghcr.io/${{ github.repository_owner }}/charts/trigger \
              --version "${{ steps.version.outputs.version }}"
            ```

            > ⚠️ This is a prerelease for testing. Do not use in production.
          edit-mode: replace
