- name: Container creation
  block:
  - name: Init mounts
    set_fact:
      mounts: "{{ mounts | default({}) }}"

  - name: Set mounts
    set_fact:
      mounts: >-
        {{ mounts | default({}) | combine({('mp'~idx): 
          ((item.split(':')[:-1] | join(':')) ~ ',mp=' ~ (item.split(':')[-1]) ~ ',ro=0,acl=1') }) }}
    loop: "{{ mount.split(',') | reject('equalto','') | select('search', ':') }}"
    loop_control:
      index_var: idx
    when:
      - mount is defined
      - mount | trim | length > 0

  - name: Set passthrough
    set_fact:
      mounts: "{{ mounts | combine({ ('dev' ~ idx): item | trim }) }}"
    loop: "{{ mount.split(',') | reject('equalto','') | select('match', '^/[^:]+$') }}"
    loop_control:
      index_var: idx
    when:
      - mount is defined
      - mount | trim | length > 0

  - name: Base capabilities
    set_fact:
      features: ['nesting=1', 'keyctl=1']

  - name: Mount share capability
    set_fact:
      features: "{{ features + ['mount=cifs'] }}"
    when:
      - not share | default(false) | bool
      - mount | default('') | trim != ''
      - PROXMOX_PASSWORD is defined
      - PROXMOX_PASSWORD != ''

  - name: Create container
    community.general.proxmox: &create_container
      vmid: "{{ id }}"
      hostname: "{{ hostname }}"
      ostemplate: "{{ os }}"
      cores: "{{ cores }}"
      memory: "{{ memory }}"
      pubkey: "{{ lookup('file', [DIR_KEYS, id ~ '.pub'] | path_join) }}"
      swap: "{{ swap }}"
      disk: "{{ disk }}"
      netif:
        net0: "name={{ lookup('env', 'PROXMOX_INTERFACE') }},gw={{ lookup('env', 'PROXMOX_GATEWAY') }},ip={{ ip }}/{{ lookup('env', 'PROXMOX_MASK') }},bridge={{ lookup('env', 'PROXMOX_BRIDGE') }}"
      features: "{{ (features if features and (PROXMOX_PASSWORD is defined and PROXMOX_PASSWORD != '') else omit) }}"
      mounts: "{{ (mounts if mounts and (PROXMOX_PASSWORD is defined and PROXMOX_PASSWORD != '') else omit) }}"
      unprivileged: "{{ (share | default(false) and mount | default('') | trim != '') | ternary(false, true) }}"
      onboot: "{{ boot }}"
      state: present
    register: container_creation

  rescue:
  - set_fact:
      os_missing: "{{ (ansible_failed_result.msg | default('')) is search('ostemplate', ignorecase=True) }}"
  - include_tasks: os.yml
    when: os_missing
  - community.general.proxmox:
      <<: *create_container
    register: container_creation
    when: os_missing
  - fail:
      msg: "{{ ansible_failed_result.msg | default('container create failed') }}"
    when: not os_missing