---
- name: Install Zabbix Agent on All Hosts
  hosts: all
  become: yes
  vars:
    zabbix_server: "192.168.99.146"
    zabbix_agent_package: "zabbix-agent"
    zabbix_agent_service: "zabbix-agent"
    zabbix_agent_config: "/etc/zabbix/zabbix_agentd.conf"
    
  tasks:
    - name: Display target host info
      debug:
        msg:
          - "Host: {{ inventory_hostname }}"
          - "System: {{ system_type | default('unknown') }}"
          - "Installing: zabbix-agent (v1)"
          - "Server: {{ zabbix_server }}"

    - name: Check if zabbix-agent2 is running
      shell: systemctl is-active zabbix-agent2
      register: agent2_status
      failed_when: false
      changed_when: false

    - name: Stop and disable zabbix-agent2 if running
      systemd:
        name: zabbix-agent2
        state: stopped
        enabled: no
      when: agent2_status.stdout == "active"
      ignore_errors: yes

    - name: Remove existing zabbix-agent2 (RHEL/CentOS/Anolis)
      package:
        name: zabbix-agent2
        state: absent
      when: 
        - ansible_os_family in ["RedHat"] or system_type in ["anolis8", "anolis7", "centos7", "centos8"]
        - agent2_status.stdout == "active"
      ignore_errors: yes

    - name: Remove existing zabbix-agent2 (Ubuntu)
      package:
        name: zabbix-agent2
        state: absent
      when: 
        - ansible_os_family == "Debian" or system_type in ["ubuntu18", "ubuntu22"]
        - agent2_status.stdout == "active"
      ignore_errors: yes

    - name: Clean up agent2 config files
      file:
        path: "{{ item }}"
        state: absent
      loop:
        - /etc/zabbix/zabbix_agent2.conf
        - /etc/zabbix/zabbix_agent2.conf.backup
        - /run/zabbix/zabbix_agent2.pid
      ignore_errors: yes

    # 使用curl直接下载，避免SSL验证问题
    - name: Download Zabbix repository RPM (CentOS 7)
      get_url:
        url: "https://repo.zabbix.com/zabbix/6.4/rhel/7/x86_64/zabbix-agent-6.4.4-release1.el7.x86_64.rpm"
        dest: "/tmp/zabbix-agent-6.4.4-release1.el7.x86_64.rpm"
        validate_certs: no
        mode: '0644'
        timeout: 60
      when: system_type == "centos7"
      register: download_result
      ignore_errors: yes

    # 如果下载失败，尝试使用wget
    - name: Download via wget if get_url failed (CentOS 7)
      shell: |
        cd /tmp
        wget --no-check-certificate https://repo.zabbix.com/zabbix/6.4/rhel/7/x86_64/zabbix-agent-6.4.4-release1.el7.x86_64.rpm
      when: 
        - system_type == "centos7"
        - download_result.failed is defined and download_result.failed
      ignore_errors: yes

    # 如果wget也失败，尝试curl
    - name: Download via curl if wget failed (CentOS 7)
      shell: |
        cd /tmp
        curl -k -O https://repo.zabbix.com/zabbix/6.4/rhel/7/x86_64/zabbix-agent-6.4.4-release1.el7.x86_64.rpm
      when: system_type == "centos7"
      ignore_errors: yes
    # 检查 RPM 包是否存在
    - name: Check if RPM package exists (CentOS 7)
      stat:
        path: "/tmp/zabbix-agent-6.4.4-release1.el7.x86_64.rpm"
      when: system_type == "centos7"
      register: rpm_file_check

    # 使用 shell 直接安装 Zabbix Agent RPM 包 (CentOS 7)
    - name: Install Zabbix Agent from RPM (CentOS 7)
      shell: |
        rpm -ivh /tmp/zabbix-agent-6.4.4-release1.el7.x86_64.rpm --force --nodeps
      when: 
        - system_type == "centos7"
        - rpm_file_check.stat.exists
      ignore_errors: no

    # 如果 RPM 安装失败，显示错误信息
    - name: Show error if RPM not found (CentOS 7)
      debug:
        msg: "错误: 无法找到或下载 Zabbix Agent RPM 包"
      when: 
        - system_type == "centos7"
        - not rpm_file_check.stat.exists

    # 清理临时文件 (CentOS 7)
    - name: Clean up RPM file (CentOS 7)
      file:
        path: "/tmp/zabbix-agent-6.4.4-release1.el7.x86_64.rpm"
        state: absent
      when: system_type == "centos7"
      ignore_errors: yes

    # 导入GPG密钥
    - name: Import Zabbix GPG keys (CentOS 7)
      shell: |
        rpm --import https://repo.zabbix.com/RPM-GPG-KEY-ZABBIX-A14FE591 || true
        rpm --import https://repo.zabbix.com/RPM-GPG-KEY-ZABBIX || true
      when: system_type == "centos7"
      ignore_errors: yes

    # 其他系统的仓库配置保持不变
    # 添加Zabbix仓库 (如果还没有)
    - name: Add Zabbix repository (CentOS 8/Anolis 8)
      dnf:
        name: "https://repo.zabbix.com/zabbix/6.4/rhel/8/x86_64/zabbix-release-6.4-1.el8.noarch.rpm"
        state: present
        disable_gpg_check: yes
      when: system_type in ["centos8", "anolis8"]
      ignore_errors: yes

    - name: Add Zabbix repository (Ubuntu 18)
      apt:
        deb: "https://repo.zabbix.com/zabbix/6.4/ubuntu/pool/main/z/zabbix-release/zabbix-release_6.4-1+ubuntu18.04_all.deb"
        state: present
      when: system_type == "ubuntu18"
      ignore_errors: yes

    - name: Add Zabbix repository (Ubuntu 22)
      apt:
        deb: "https://repo.zabbix.com/zabbix/6.4/ubuntu/pool/main/z/zabbix-release/zabbix-release_6.4-1+ubuntu22.04_all.deb"
        state: present
      when: system_type == "ubuntu22"
      ignore_errors: yes

    - name: Update package cache (Ubuntu)
      apt:
        update_cache: yes
      when: ansible_os_family == "Debian"
      ignore_errors: yes

    - name: Install Zabbix Agent (CentOS 8/Anolis 8)
      dnf:
        name: "{{ zabbix_agent_package }}"
        state: present
      when: system_type in ["centos8", "anolis8"]

    - name: Install Zabbix Agent (Ubuntu)
      apt:
        name: "{{ zabbix_agent_package }}"
        state: present
      when: ansible_os_family == "Debian" or system_type in ["ubuntu18", "ubuntu22"]

    - name: Backup original config if exists
      copy:
        src: "{{ zabbix_agent_config }}"
        dest: "{{ zabbix_agent_config }}.backup-{{ ansible_date_time.epoch }}"
        remote_src: yes
        backup: no
      ignore_errors: yes

    - name: Ensure Zabbix directories exist
      file:
        path: "{{ item }}"
        state: directory
        owner: zabbix
        group: zabbix
        mode: '0755'
      loop:
        - /var/log/zabbix
        - /run/zabbix
        - /etc/zabbix/zabbix_agentd.d
      ignore_errors: yes

    - name: Configure Zabbix Agent
      template:
        src: zabbix_agentd.conf.j2
        dest: "{{ zabbix_agent_config }}"
        owner: root
        group: root
        mode: '0644'
        backup: yes
      notify: restart zabbix-agent

    - name: Start and enable Zabbix Agent
      systemd:
        name: "{{ zabbix_agent_service }}"
        state: started
        enabled: yes
        daemon_reload: yes

    - name: Wait for agent to start
      wait_for:
        port: 10050
        host: "{{ ansible_default_ipv4.address | default('127.0.0.1') }}"
        delay: 2
        timeout: 30
      ignore_errors: yes

    - name: Configure firewall for RHEL/CentOS (if firewalld is running)
      firewalld:
        port: "10050/tcp"
        permanent: yes
        state: enabled
        immediate: yes
      when: 
        - ansible_os_family in ["RedHat"] or system_type in ["anolis8", "anolis7", "centos7", "centos8"]
      ignore_errors: yes

    - name: Configure firewall for Ubuntu (if ufw is active)
      ufw:
        rule: allow
        port: '10050'
        proto: tcp
      when: ansible_os_family == "Debian" or system_type in ["ubuntu18", "ubuntu22"]
      ignore_errors: yes

    - name: Test agent connectivity
      shell: |
        # 测试agent是否响应
        if command -v zabbix_agentd >/dev/null; then
          zabbix_agentd -t agent.ping 2>/dev/null || echo "Test failed"
        fi
        
        # 检查端口监听
        if ss -tlnp | grep -q ":10050"; then
          echo "Port 10050 listening OK"
        else
          echo "Port 10050 NOT listening"
        fi
        
        # 检查服务状态
        systemctl is-active zabbix-agent || echo "Service not active"
      register: connectivity_test
      changed_when: false
      failed_when: false

    - name: Display test results
      debug:
        msg: 
          - "Host: {{ inventory_hostname }}"
          - "Connectivity test: {{ connectivity_test.stdout_lines }}"

    # 清理临时文件
    - name: Clean up temporary files
      file:
        path: "/tmp/zabbix-release-6.4.4-1.el7.noarch.rpm"
        state: absent
      when: system_type == "centos7"
      ignore_errors: yes
        
  handlers:
    - name: restart zabbix-agent
      systemd:
        name: "{{ zabbix_agent_service }}"
        state: restarted
        daemon_reload: yes
