- name: Environment
  block:

  - name: Get environment configuration
    block:
    - name: Ensure configuration file
      ansible.builtin.stat:
        path: "{{ PROXMOX_DIR }}/local/{{ item }}"
      loop:
        - config.local.json
        - config.json
      register: config_files

    - name: Load configuration file
      ansible.builtin.include_vars:
        file: "{{ config_files.results | selectattr('stat.exists') | map(attribute='stat.path') | first | default('none') }}"
        name: config

  - name: Proxmox configuration
    block:
    - name: Set Proxmox credentials
      ansible.builtin.set_fact:
        PROXMOX_HOST:     "{{ (config.proxmox.host     if (config.proxmox is defined and 'host'     in config.proxmox) else none) | default(lookup('env', 'PROXMOX_HOST'))     | default('') }}"
        PROXMOX_USER:     "{{ (config.proxmox.user     if (config.proxmox is defined and 'user'     in config.proxmox) else none) | default(lookup('env', 'PROXMOX_USER'))     | default('') }}"
        PROXMOX_PASSWORD: "{{ (config.proxmox.password if (config.proxmox is defined and 'password' in config.proxmox) else none) | default(lookup('env', 'PROXMOX_PASSWORD')) | default('') }}"
        PROXMOX_TOKEN:    "{{ (config.proxmox.token    if (config.proxmox is defined and 'token'    in config.proxmox) else none) | default(lookup('env', 'PROXMOX_TOKEN'))    | default('') }}"
        PROXMOX_SECRET:   "{{ (config.proxmox.secret   if (config.proxmox is defined and 'secret'   in config.proxmox) else none) | default(lookup('env', 'PROXMOX_SECRET'))   | default('') }}"

    - name: Get Proxmox privileges
      block:
        - name: Get root user ticket
          uri:
            url: "https://{{ PROXMOX_HOST }}:8006/api2/json/access/ticket"
            method: POST
            body:
              username: "{{ PROXMOX_USER }}"
              password: "{{ PROXMOX_PASSWORD }}"
            body_format: json
            validate_certs: no
          register: proxmox_login
          when: (PROXMOX_PASSWORD | default('')) | trim != ''