---
- set_fact:
    content: "{{ lookup('file', default_kubeconfig_path) | from_yaml }}"
    custom_content: {}
    clusters: []

- set_fact:
    custom_content: "{{ custom_content | combine({item.key: item.value}) }}"
  when: "{{ item.key not in ['clusters'] }}"
  with_dict: "{{ content }}"

- set_fact:
    clusters: "{{ clusters + [item | combine({'cluster': {'certificate-authority-data': omit}}, recursive=true)] }}"
  with_items: "{{ content.clusters }}"

- set_fact:
    custom_content: "{{ custom_content | combine({'clusters': clusters}) }}"

- name: create temporary file for ca_cert
  tempfile:
    suffix: .cacert
  register: ca_file

- name: copy content into certificate file
  copy:
    content: "{{ content.clusters.0.cluster['certificate-authority-data'] | b64decode }}"
    dest: "{{ ca_file.path }}"

- name: create temporary file to save config in
  tempfile:
    suffix: .config
  register: tfile

- name: create custom config
  copy:
    content: "{{ custom_content | to_yaml }}"
    dest: "{{ tfile.path }}"

- block:
    - name: Install Redis chart without ca_cert (should fail)
      helm:
        binary_path: "{{ helm_binary }}"
        chart_repo_url: https://charts.bitnami.com/bitnami
        chart_ref: redis
        namespace: "{{ helm_namespace }}"
        create_namespace: true
        name: redis-chart
        chart_version: '17.0.5'
        release_values:
          architecture: standalone
        release_state: present
        kubeconfig: "{{ tfile.path }}"
      ignore_errors: true
      register: _install

    - name: assert task failed
      assert:
        that:
          - _install is failed
          - '"Error: Kubernetes cluster unreachable" in _install.msg'

    - name: Test helm modules using in-memory kubeconfig
      include_tasks: "tests_helm_auth.yml"
      vars:
        test_kubeconfig: "{{ tfile.path }}"
        test_ca_cert: "{{ ca_file.path }}"

  vars:
    helm_namespace: "{{ test_namespace[1] }}"

  always:
    - name: Delete temporary file
      file:
        state: absent
        path: "{{ tfile.path }}"
      ignore_errors: true
