---
- block:

    - name: Check if the statefulset application exists.
      shell: kubectl get pods -n {{ app_ns }} -l {{ app_label }}
      register: pods
      failed_when: "'No resources found' in pods.stdout"

    - name: Obtaining PVCs related to the application.
      shell: kubectl get pvc -n {{ app_ns }} -l {{ app_label }}  --no-headers -o custom-columns=:.metadata.name
      register: pvc_list

    - name: Obtaining the PV names.
      shell: kubectl get pvc -l {{ app_label }} -n {{ app_ns }} --no-headers -o custom-columns=:.spec.volumeName
      register: pv_list

     ## Replacing the item names in the respective deployer spec file.
    - name: Replace the PVC name in application deployer spec.
      replace:
        path: "{{ app_deployer }}"
        regexp: "testclaim"
        replace: "{{ lookup('env','APP_PVC') }}"
      when: app_pvc is defined

    - name: Replace the storageclass placeholder with provider
      replace:
        path: "{{ app_deployer }}"
        regexp: "testclass"
        replace: "{{ lookup('env','PROVIDER_STORAGE_CLASS') }}"
      when: storage_class is defined

    - block:

        - name: Get the application label values from env
          set_fact:
            app_lkey: "{{ app_label.split('=')[0] }}"
            app_lvalue: "{{ app_label.split('=')[1] }}"

        - name: Replace the application label placeholder
          replace:
            path: "{{ app_deployer }}"
            regexp: "lkey: lvalue"
            replace: "{{ app_lkey }}: {{ app_lvalue }}"

      when: app_label is defined

    - name: Delete the application and its related service.
      shell: kubectl delete -f {{ app_deployer }} -n {{ app_ns }}
      register: app_status
      until: 'app_status.rc == 0'
      delay: 5
      retries: 60

    - name: Deleting the PVC
      shell: kubectl delete pvc {{ item }} -n {{ app_ns }}
      args:
        executable: /bin/bash
      with_items:
        - "{{ pvc_list.stdout_lines }}"

    - name: Check if the PVCs are deleted
      shell: kubectl get pvc -n {{ app_ns }}
      register: list_pvc
      until: "'No resources found' in list_pvc.stderr"
      delay: 30
      retries: 15

- name: Delete the namespace.
  shell: kubectl delete ns {{ app_ns }}
  args:
    executable: /bin/bash

