---
- name: "Set Log File Info"
  ansible.builtin.set_fact:
    zabbix_agent_logfile: "{{ zabbix_agent_win_logfile is defined | ternary(zabbix_agent_win_logfile, zabbix_agent2_win_logfile) | default(_win_logfile) }}"

- name: "Set Include Path Info"
  ansible.builtin.set_fact:
    zabbix_agent_include_dir: "{{ zabbix_agent_win_include is defined | ternary(zabbix_agent_win_include, zabbix_agent2_win_include) | default(_win_include) }}"

- name: "Set Control Socket"
  ansible.builtin.set_fact:
    zabbix_agent_controlsocket: "\\\\.\\pipe\\agent.sock"

- name: "Set default ip address for zabbix_agent_ip"
  ansible.builtin.set_fact:
    zabbix_agent_ip: "{{ hostvars[inventory_hostname]['ansible_ip_addresses'] | ansible.utils.ipv4 | first }}"
  when:
    - zabbix_agent_ip is not defined
    - "'ansible_ip_addresses' in hostvars[inventory_hostname]"
  tags:
    - config

- name: "Windows | Configure zabbix-agent"
  ansible.windows.win_template:
    src: agent.conf.j2
    dest: "{{ zabbix_win_install_dir_conf }}\\{{ zabbix_win_config_name }}"
  notify: restart win zabbix agent
  tags:
    - config

- name: "Windows | Set service startup mode to auto, ensure it is started and set auto-recovery"
  ansible.windows.win_service:
    name: "{{ zabbix_win_svc_name }}"
    start_mode: auto
    state: started
    failure_actions:
      - type: restart
        delay_ms: 5000
      - type: restart
        delay_ms: 10000
      - type: restart
        delay_ms: 20000
    failure_reset_period_sec: 86400
  tags:
    - config

- name: "Windows | Check firewall service"
  ansible.windows.win_service_info:
    name: MpsSvc
  register: firewall_info
  when: zabbix_win_firewall_management
  tags:
    - config

- name: "Windows | Firewall rule"
  community.windows.win_firewall_rule:
    name: "{{ zabbix_win_svc_name }}"
    localport: "{{ zabbix_agent_listenport }}"
    action: allow
    direction: in
    protocol: tcp
    state: present
    enabled: true
  when:
    - zabbix_win_firewall_management
    - firewall_info.services[0].state == 'started' or firewall_info.services[0].start_mode == 'auto'
  tags:
    - config
