---
- name: Test CRDs
  vars:
    test_chart: "test-crds"
  block:
    - name: Create namespace
      k8s:
        kind: Namespace
        name: "{{ helm_namespace }}"

    - name: Copy test chart
      copy:
        src: "{{ test_chart }}"
        dest: "/tmp/helm_test_crds/"

    - name: Install chart while skipping CRDs
      helm:
        binary_path: "{{ helm_binary }}"
        chart_ref: "/tmp/helm_test_crds/{{ test_chart }}"
        namespace: "{{ helm_namespace }}"
        name: test-crds
        skip_crds: true
      register: install

    - assert:
        that:
          - install is changed
          - install.status.name == "test-crds"

    - name: Fail to create custom resource
      k8s:
        definition:
          apiVersion: example.com/v1
          kind: Foo
          metadata:
            namespace: "{{ helm_namespace }}"
            name: test-foo
          foobar: footest
      ignore_errors: true
      register: result

    - assert:
        that:
          - result is failed
          - "result.msg.startswith('Failed to find exact match for example.com/v1.Foo')"

    # Helm won't install CRDs into an existing release, so we need to delete this, first
    - name: Uninstall chart
      helm:
        binary_path: "{{ helm_binary }}"
        namespace: "{{ helm_namespace }}"
        name: test-crds
        state: absent

    - name: Install chart with CRDs
      helm:
        binary_path: "{{ helm_binary }}"
        chart_ref: "/tmp/helm_test_crds/{{ test_chart }}"
        namespace: "{{ helm_namespace }}"
        name: test-crds

    - name: Create custom resource
      k8s:
        definition:
          apiVersion: example.com/v1
          kind: Foo
          metadata:
            namespace: "{{ helm_namespace }}"
            name: test-foo
          foobar: footest
      register: result

    - assert:
        that:
          - result is changed
          - result.result.foobar == "footest"

  always:
    - name: Remove chart
      file:
        path: "/tmp/helm_test_crds"
        state: absent
      ignore_errors: true

    - name: Remove namespace
      k8s:
        kind: Namespace
        name: "{{ helm_namespace }}"
        state: absent
        wait: true
        wait_timeout: 180
      ignore_errors: true

    # CRDs aren't deleted with a namespace, so we need to manually delete it
    - name: Remove CRD
      k8s:
        kind: CustomResourceDefinition
        name: foos.example.com
        state: absent
      ignore_errors: true
