- name: Environment
  include_tasks: env.yml

- name: Get architecture
  uri:
    url: "https://{{ PROXMOX_HOST }}:8006/api2/json/nodes/{{ PROXMOX_NODE }}/status"
    method: GET
    headers: "{{ proxmox_auth }}"
    return_content: yes
    validate_certs: no
  register: status

- name: Set OS template
  set_fact:
    os: |-
      {{ OS | default(PROXMOX_STORAGE ~ '/' ~ PROXMOX_TEMPLATE ~ '_' ~
        ('arm64' if (status.json.data['current-kernel'].machine | default('x86_64')
        | lower is search('arm|aarch64')) else 'amd64') ~ '.tar.zst' ) }}

- name: Container orchestration
  block:
  - name: Check container
    community.general.proxmox_vm_info:
      vmid: "{{ id }}"
    register: container_exists

  - name: Remove existing container
    include_tasks: remove.yml
    when: (container_exists.proxmox_vms | default([]) | length) > 0

  - name: Create container
    include_tasks: create.yml

  - name: Start container
    include_tasks: start.yml

  - name: Add container
    include_tasks: add.yml

  module_defaults:
    community.general.proxmox: "{{ proxmox_cred | combine({'timeout': 120}, recursive=True) }}"
    community.general.proxmox_vm_info: "{{ proxmox_cred }}"
    uri:
      return_content: yes
      validate_certs: no