---
- name: Check if proxy group exists
  uri:
    url: "{{ zabbix_api_url }}"
    method: POST
    body_format: json
    body:
      jsonrpc: "2.0"
      method: "proxygroup.get"
      params:
        filter:
          name: "{{ clustename }}"
      id: 2
    headers:
      Content-Type: "application/json"
      Authorization: "Bearer {{ zabbix_auth_token }}"
  register: proxygroup_query
  run_once: true              # Run this task only once
  
- name: Print proxygroup_query
  debug:
    msg: "{{ proxygroup_query }}"
  run_once: true              # Run this task only once
  
- name: Create proxy group if not exists
  uri:
    url: "{{ zabbix_api_url }}"
    method: POST
    body_format: json
    body:
      jsonrpc: "2.0"
      method: "proxygroup.create"
      params:
        name: "{{ clustename }}"
        failover_delay: "1m"
        min_online: 1
      id: 1
    headers:
      Content-Type: "application/json"
      Authorization: "Bearer {{ zabbix_auth_token }}"
  when: proxygroup_query.json.result | length == 0
  register: proxygroup_create
  run_once: true              # Run this task only once

- set_fact:
    proxygroup_id: >-
      {{
        proxygroup_create.json.result.proxy_groupid[0]
        if not proxygroup_create.skipped
        else proxygroup_query.json.result[0].proxy_groupid
      }}



- name: Check if proxy exists
  uri:
    url: "{{ zabbix_api_url }}"
    method: POST
    body_format: json
    body:
      jsonrpc: "2.0"
      method: "proxy.get"
      params:
        filter:
          name: "{{ inventory_hostname }}"
      id: 2
    headers:
      Content-Type: "application/json"
      Authorization: "Bearer {{ zabbix_auth_token }}"
  register: proxy_check

- name: Print proxy_check
  debug:
    msg: "{{ proxy_check }}"

- name: Create proxy if not exists
  uri:
    url: "{{ zabbix_api_url }}"
    method: POST
    body_format: json
    body:
      jsonrpc: "2.0"
      method: "proxy.create"
      params:
        name: "{{ inventory_hostname }}"
        proxy_groupid: "{{ proxygroup_id }}"
        operating_mode: 0
        local_address: "{{ ansible_default_ipv4.address }}"
        port: "10051"
      id: 3
    headers:
      Content-Type: "application/json"
      Authorization: "Bearer {{ zabbix_auth_token }}"
  when: proxy_check.json.result | length == 0
  register: proxy_check2


- name: Print proxy_check
  debug:
    msg: "{{ proxy_check2 }}"
  run_once: true              # Run this task only once