name: k8s

on:
  push:
    branches: ["main"]
    paths:
      - 'helm/**' # only execute if we have helm chart changes
  pull_request:
    branches: ["main"]
    paths:
      - 'helm/**'

jobs:
  lint:
    name: Lint Helm chart
    runs-on: ubuntu-latest
    outputs:
      changed: ${{ steps.list-changed.outputs.changed }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: azure/setup-helm@v3
        with:
          version: v3.10.0
      - uses: actions/setup-python@v4
        with:
          python-version: 3.11
          check-latest: true
      - uses: helm/chart-testing-action@v2.3.1
      - name: Get changed status
        id: list-changed
        run: |
          changed=$(ct list-changed --config helm/ct.yaml --target-branch ${{ github.event.repository.default_branch }})
          if [[ -n "$changed" ]]; then
              echo "::set-output name=changed::true"
          fi

      - name: Run lint
        run: ct lint --config helm/ct.yaml

  # only bother to run if lint step reports a change to the helm chart
  install:
    needs:
      - lint
    if: ${{ needs.lint.outputs.changed == 'true' }}
    name: Install Helm charts
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: ${{ inputs.checkoutCommit }}
      - name: Install Kubernetes tools
        uses: yokawasa/action-setup-kube-tools@v0.8.2
        with:
          setup-tools: |
            helmv3
          helm: "3.10.3"
      - uses: actions/setup-python@v4
        with:
          python-version: "3.10"
      - name: Set up chart-testing
        uses: helm/chart-testing-action@v2.3.1
      - name: Create k3d cluster
        uses: nolar/setup-k3d-k3s@v1
        with:
          version: v1.28
      - name: Remove node taints
        run: |
          kubectl taint --all=true nodes node.cloudprovider.kubernetes.io/uninitialized- || true
      - name: Run chart-testing (install)
        run: ct install --config helm/ct.yaml

      # Install the chart using helm directly and test with create-account
      - name: Install chart
        run: |
          helm install --values helm/dendrite/ci/ct-postgres-sharedsecret-values.yaml dendrite helm/dendrite
      - name: Wait for Postgres and Dendrite to be up
        run: |
          kubectl wait --for=condition=ready --timeout=90s pod -l app.kubernetes.io/name=postgresql || kubectl get pods -A
          kubectl wait --for=condition=ready --timeout=90s pod -l app.kubernetes.io/name=dendrite || kubectl get pods -A
          kubectl get pods -A
          kubectl get services
          kubectl get ingress
          kubectl logs -l app.kubernetes.io/name=dendrite
      - name: Run create account
        run: |
          podName=$(kubectl get pods -l app.kubernetes.io/name=dendrite -o name)
          kubectl exec "${podName}" -- /usr/bin/create-account -username alice -password somerandompassword