---
- name: Stat XDG_RUNTIME_DIR
  stat:
    path: "{{ __podman_xdg_runtime_dir }}"
  register: __podman_xdg_stat
  when:
    - __podman_rootless | bool
    - __podman_xdg_runtime_dir | d("") | length > 0

- name: Stop and disable service
  systemd:
    name: "{{ __podman_service_name.stdout }}"
    scope: "{{ __podman_systemd_scope }}"
    state: stopped
    enabled: false
  become: "{{ __podman_rootless | ternary(true, omit) }}"
  become_user: "{{ __podman_rootless | ternary(__podman_user, omit) }}"
  environment:
    XDG_RUNTIME_DIR: "{{ __podman_xdg_runtime_dir }}"
  register: __podman_service_status
  when: not __podman_rootless or __podman_xdg_stat.stat.exists
  failed_when:
    - __podman_service_status is failed
    - not __podman_service_status.stdout is search(__service_error)
  vars:
    __service_error: Could not find the requested service

- name: Check if kube file exists
  stat:
    path: "{{ __podman_kube_file }}"
  register: __podman_kube_file_stat

- name: Remove pod/containers
  containers.podman.podman_play: "{{ __podman_kube_spec |
    combine({'kube_file': __podman_kube_file}) }}"
  environment:
    XDG_RUNTIME_DIR: "{{ __podman_xdg_runtime_dir }}"
  become: "{{ __podman_rootless | ternary(true, omit) }}"
  become_user: "{{ __podman_rootless | ternary(__podman_user, omit) }}"
  register: __podman_removed
  when:
    - not __podman_rootless or __podman_xdg_stat.stat.exists
    - __podman_kube_file_stat.stat.exists

- name: Remove kubernetes yaml file
  file:
    path: "{{ __podman_kube_file }}"
    state: absent

- name: Prune images no longer in use
  command: podman image prune -f
  environment:
    XDG_RUNTIME_DIR: "{{ __podman_xdg_runtime_dir }}"
  become: "{{ __podman_rootless | ternary(true, omit) }}"
  become_user: "{{ __podman_rootless | ternary(__podman_user, omit) }}"
  when: __podman_removed is changed  # noqa no-handler
  changed_when: true

- name: Manage linger
  include_tasks: manage_linger.yml
  vars:
    __podman_item_state: absent
