# SPDX-License-Identifier: MIT
---
- name: Set variables part 1
  set_fact:
    __podman_user: "{{ __podman_secret_item['run_as_user'] |
      d(podman_run_as_user) }}"

- name: Set variables part 2
  set_fact:
    __podman_rootless: "{{ __podman_user != 'root' }}"
    __podman_xdg_runtime_dir: >-
      /run/user/{{ ansible_facts["getent_passwd"][__podman_user][1] }}

- name: Manage linger
  include_tasks: manage_linger.yml
  vars:
    __podman_item_state: "{{ __podman_secret_item.state | d('present') }}"

- 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

# if XDG_RUNTIME_DIR does not exist, this means linger
# was already canceled, which means the user is attempting
# to remove more than once
# We use __params here because the Ansible module code will convert a `data`
# parameter string that looks like JSON e.g. {"test": "string"} to a dict or
# list - there seems to be no way to prevent that - but if we construct the
# parameter dict to pass to podman_secret, it seems to preserve the original
# data types
- name: Manage each secret
  containers.podman.podman_secret: "{{ __params }}"
  environment:
    XDG_RUNTIME_DIR: "{{ __podman_xdg_runtime_dir }}"
  become: "{{ __podman_rootless | ternary(true, omit) }}"
  become_user: "{{ __podman_rootless | ternary(__podman_user, omit) }}"
  when: not __podman_rootless or __podman_xdg_stat.stat.exists
  no_log: true
  vars:
    __params: |
      {% set rc = {} %}
      {% set supported_params = ['data', 'driver', 'driver_opts', 'executable',
                                 'force', 'name', 'skip_existing', 'state'] %}
      {% for key in supported_params %}
      {%   if key in __podman_secret_item %}
      {%     set _ = rc.__setitem__(key, __podman_secret_item[key]) %}
      {%   endif %}
      {% endfor %}
      {{ rc }}
