- name: Install Zabbix Proxy on Debian 13
  vars:
    zabbix_version: "7.4"
    zabbix_server_ip: "192.168.77.101"
    zabbix_proxy_name: "{{ inventory_hostname }}"
    zabbix_db_file: "/var/lib/zabbix/zabbix_proxy.db"
    zabbix_db_type: "sqlite"   # sqlite | mysql | postgres
    zabbix_api_url: "https://zabbix.sectorq.eu/api_jsonrpc.php"
  become: "{{ 'no' if inventory_hostname == 'nas.home.lan' else 'yes' }}"
  block:
    # ==========================================================
    # Install repository
    # ==========================================================
    - name: Gather facts
      ansible.builtin.setup:

    - name: Show default IP
      ansible.builtin.debug:
        msg: "{{ ansible_default_ipv4.address }}"
    - name: Install base packages
      ansible.builtin.dnf:
        name:
          - wget
          - gnupg
        state: present
        
    # - name: Create apt proxy file
    #   ansible.builtin.copy:
    #     dest: /etc/apt/apt.conf.d/02proxy
    #     content: |
    #       Acquire::http::Proxy "http://192.168.77.101:3142";
    #       Acquire::https::Proxy "false";

    # ==========================================================
    # Import Zabbix GPG key
    # ==========================================================

    - name: Import Zabbix GPG key
      ansible.builtin.rpm_key:
        state: present
        key: https://repo.zabbix.com/RPM-GPG-KEY-ZABBIX-08EFA7DD


    # ==========================================================
    # Install Zabbix repository
    # ==========================================================

    - name: Install Zabbix repository
      ansible.builtin.dnf:
        name: "https://repo.zabbix.com/zabbix/{{ zabbix_version }}/release/rocky/9/noarch/zabbix-release-latest-{{ zabbix_version }}.el9.noarch.rpm"
        state: present


    - name: Install Zabbix repository
      ansible.builtin.dnf:
        name: /tmp/zabbix-release.rpm
        state: present
    - name: Update dnf cache
      ansible.builtin.dnf:
        update_cache: true

    # ==========================================================
    # Install proxy based on DB type
    # ==========================================================

    - name: Install SQLite proxy
      ansible.builtin.dnf:
        name:
          - zabbix-proxy-sqlite3
          - sqlite3
        state: present
      when: zabbix_db_type == "sqlite"

    - name: Install MySQL proxy
      ansible.builtin.dnf:
        name:
          - zabbix-proxy-mysql
          - default-mysql-client
        state: present
      when: zabbix_db_type == "mysql"

    - name: Install PostgreSQL proxy
      ansible.builtin.dnf:
        name:
          - zabbix-proxy-pgsql
          - postgresql-client
        state: present
      when: zabbix_db_type == "postgres"

    - name: Install Zabbix agent
      ansible.builtin.dnf:
        name: zabbix-agent2
        state: present

    # ==========================================================
    # SQLite setup
    # ==========================================================

    - name: Ensure Zabbix directory ownership (SQLite)
      file:
        path: /var/lib/zabbix
        owner: zabbix
        group: zabbix
        recurse: yes
      when: zabbix_db_type == "sqlite"


    # ==========================================================
    # MySQL setup
    # ==========================================================

    - name: Import MySQL schema
      shell: |
        zcat /usr/share/zabbix/mysql/proxy.sql.gz | \
        mysql -h {{ zabbix_db_host }} \
              -u {{ zabbix_db_user }} \
              -p{{ zabbix_db_password }} \
              {{ zabbix_db_name }}
      when: zabbix_db_type == "mysql"

    # ==========================================================
    # PostgreSQL setup
    # ==========================================================

    - name: Import PostgreSQL schema
      shell: |
        zcat /usr/share/zabbix/postgresql/proxy.sql.gz | \
        PGPASSWORD={{ zabbix_db_password }} psql \
        -h {{ zabbix_db_host }} \
        -U {{ zabbix_db_user }} \
        {{ zabbix_db_name }}
      become_user: postgres
      when: zabbix_db_type == "postgres"

    - name: Configure Zabbix agent
      lineinfile:
        path: /etc/zabbix/zabbix_agent2.conf
        regexp: "^{{ item.key }}="
        line: "{{ item.key }}={{ item.value }}"
      loop: >-
          {{ [
            {'key': 'Server', 'value': '127.0.0.1'},
            {'key': 'ServerActive', 'value': 'debian13-vm01.home.lan;debian13-vm02.home.lan;debian13-vm03.home.lan;debian13-vm04.home.lan;debian13-vm05.home.lan'},
            {'key': 'Hostname', 'value': zabbix_proxy_name},
            {'key': 'HostMetadata', 'value': 'linux,jaydee'},
          ]
          }}
         
    # ==========================================================
    # Configure proxy
    # ==========================================================

    - name: Configure Zabbix proxy
      lineinfile:
        path: /etc/zabbix/zabbix_proxy.conf
        regexp: "^{{ item.key }}="
        line: "{{ item.key }}={{ item.value }}"
      loop: >-
        {{
          [
            {'key': 'Server', 'value': zabbix_server_ip},
            {'key': 'Hostname', 'value': zabbix_proxy_name},
            {'key': 'ProxyMode', 'value': '0'}
          ]
          +
          (
            (zabbix_db_type == "sqlite")
            | ternary(
                [
                  {'key': 'DBName', 'value': zabbix_db_file}
                ],
                [
                  {'key': 'DBName', 'value': zabbix_db_name},
                  {'key': 'DBUser', 'value': zabbix_db_user},
                  {'key': 'DBPassword', 'value': zabbix_db_password},
                  {'key': 'DBHost', 'value': zabbix_db_host}
                ]
              )
          )
        }}


    # ==========================================================
    # Start service
    # ==========================================================

    - name: Restart Zabbix proxy
      systemd:
        name: zabbix-proxy
        state: restarted
        enabled: yes

    - name: Restart Zabbix agent
      systemd:
        name: zabbix-agent2
        state: restarted
        enabled: yes

    - 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: "{{ zabbix_proxy_name }}"
          id: 2
        headers:
          Content-Type: "application/json"
          Authorization: "Bearer {{ zabbix_auth_token }}"
      register: proxy_check
    - name: Print proxy_check
      debug:
        msg: "{{ proxy_check }}"
    - name: Print ansible_default_ipv4.address
      debug:
        msg: "{{ ansible_default_ipv4.address }}"

    - 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: "{{ zabbix_proxy_name }}"
            proxy_groupid: 1
            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 }}"