---
- block:
    - set_fact:
        delete_namespace: delete

    - name: Ensure namespace exists
      k8s:
        definition:
          apiVersion: v1
          kind: Namespace
          metadata:
            name: "{{ delete_namespace }}"

    - name: Add a daemonset
      k8s:
        definition:
          apiVersion: apps/v1
          kind: DaemonSet
          metadata:
            name: delete-daemonset
            namespace: "{{ delete_namespace }}"
          spec:
            selector:
              matchLabels:
                app: "{{ k8s_pod_name }}"
            template: "{{ k8s_pod_template }}"
        wait: yes
        wait_timeout: 180
      vars:
        k8s_pod_name: delete-ds
        k8s_pod_image: gcr.io/kuar-demo/kuard-amd64:1
      register: ds

    - name: Check that daemonset wait worked
      assert:
        that:
          - ds.result.status.currentNumberScheduled == ds.result.status.desiredNumberScheduled

    - name: Check if pods exist
      k8s_info:
        namespace: "{{ delete_namespace }}"
        kind: Pod
        label_selectors:
          - "app={{ k8s_pod_name }}"
      vars:
        k8s_pod_name: delete-ds
      register: pods_create

    - name: Assert that there are pods
      assert:
        that:
          - pods_create.resources

    - name: Remove the daemonset
      k8s:
        kind: DaemonSet
        name: delete-daemonset
        namespace: "{{ delete_namespace }}"
        state: absent
        wait: yes

    - name: Show status of pods
      k8s_info:
        namespace: "{{ delete_namespace }}"
        kind: Pod
        label_selectors:
          - "app={{ k8s_pod_name }}"
      vars:
        k8s_pod_name: delete-ds

    - name: Wait for background deletion
      pause:
        seconds: 30

    - name: Check if pods still exist
      k8s_info:
        namespace: "{{ delete_namespace }}"
        kind: Pod
        label_selectors:
          - "app={{ k8s_pod_name }}"
      vars:
        k8s_pod_name: delete-ds
      register: pods_delete

    - name: Assert that deleting the daemonset deleted the pods
      assert:
        that:
          - not pods_delete.resources

  always:
    - name: Remove namespace
      k8s:
        kind: Namespace
        name: "{{ delete_namespace }}"
        state: absent
