- name: Install Zabbix Proxy on Debian 13
  vars:
    zabbix_version: "7.4"
    zabbix_server_ip: "192.168.77.101"
    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"
    zabbix_var_lib_path: "/var/lib/zabbix"
    zabbix_config_path: "/etc/zabbix"
    zabbix_log_path: "/var/log/zabbix"
  become: "{{ 'no' if inventory_hostname == 'nas.home.lan' else 'yes' }}"
  block:
    # ==========================================================
    # Install repository
    # ==========================================================
    - name: Gather facts
      ansible.builtin.setup:

    - name: Set proxy group name
      set_fact:
        clustename: "rocky9"

    - name: Allow user to start/stop zabbix-proxy with sudo without password
      ansible.builtin.copy:
        dest: "/etc/sudoers.d/{{ zabbix_user }}-zabbix-proxy"
        content: "{{ zabbix_user }} ALL=(ALL) NOPASSWD: /bin/systemctl start zabbix-proxy, /bin/systemctl stop zabbix-proxy"
        owner: root
        group: root
        mode: '0440'


    - name: Configure global DNF proxy
      ansible.builtin.lineinfile:
        path: /etc/dnf/dnf.conf
        regexp: '^proxy='
        line: 'proxy=http://{{ dnf_proxy_host }}:{{ dnf_proxy_port }}'
        insertafter: '^\[main\]'
        state: present
        backup: yes
      when: ansible_os_family == "RedHat"

    - name: Install base packages
      ansible.builtin.dnf:
        name:
          - wget
          - gnupg
        state: present
        
    # ==========================================================
    # Import Zabbix GPG key
    # ==========================================================

    # - name: Import Zabbix 7.4 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-{{ zabbix_version }}-3.el9.noarch.rpm"
        state: present
        disable_gpg_check: true
    # ==========================================================
    # Install proxy based on DB type
    # ==========================================================

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

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

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

    - name: Install Zabbix agent
      ansible.builtin.dnf:
        name: zabbix-agent2
        state: present
      register: zabbix_agent_install
      until: zabbix_agent_install is succeeded
      retries: 3
      delay: 5
    # ==========================================================
    # 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: "{{ clustename }}-vm01.home.lan;{{ clustename }}-vm02.home.lan;{{ clustename }}-vm03.home.lan;{{ clustename }}-vm04.home.lan;{{ clustename }}-vm05.home.lan;rocky9-vm05.home.lan" }
        - { key: "Hostname", value: "{{ inventory_hostname }}" }
        - { key: "HostMetadata", value: "linux,jaydee,auto_proxy" }
        - { key: "SourceIP", value: "{{ ansible_default_ipv4.address }}" }
     
              
    # ==========================================================
    # 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': inventory_hostname },
            {'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: Check SELinux status
      command: getenforce
      register: selinux_status
      changed_when: false
      
    - name: Display SELinux status
      debug:
        msg: "SELinux is {{ selinux_status.stdout }}"
        
    - name: Add SELinux file context for Zabbix var_lib
      sefcontext:
        target: "{{ zabbix_var_lib_path }}(/.*)?"
        setype: zabbix_var_lib_t
        state: present
      when: ansible_selinux.status == "enabled"
      
    - name: Add SELinux file context for Zabbix logs
      sefcontext:
        target: "{{ zabbix_log_path }}(/.*)?"
        setype: zabbix_log_t
        state: present
      when: ansible_selinux.status == "enabled"
      
    - name: Restore SELinux contexts for Zabbix directories
      command: restorecon -R {{ item }}
      loop:
        - "{{ zabbix_var_lib_path }}"
      when: ansible_selinux.status == "enabled"

    - 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: Create hosts / proxies in zabbix
      ansible.builtin.include_tasks: "configure.yml"
