---
- name: Test Zabbix Agent2 installation on specific hosts
  hosts: test_hosts
  become: yes
  serial: 1
  vars:
    zabbix_server: "{{ zabbix_server_ip }}"
    zabbix_server_active: "{{ zabbix_server_ip }}"
  
  pre_tasks:
    - name: Display host information
      debug:
        msg:
          - "Host: {{ inventory_hostname }}"
          - "System: {{ system_type }}"
          - "User: {{ ansible_user }}"
          - "Python: {{ ansible_python_interpreter }}"

    - name: Check disk space
      shell: df -h /
      register: disk_space
      
    - name: Display disk space
      debug:
        var: disk_space.stdout_lines

    - name: Ensure sufficient disk space (at least 1GB free)
      shell: |
        available=$(df / | tail -1 | awk '{print $4}')
        if [ $available -lt 1000000 ]; then
          echo "Warning: Less than 1GB available space"
          exit 1
        fi
      failed_when: false
      register: space_check

    - name: Clean up if space is low
      shell: |
        yum clean all 2>/dev/null || dnf clean all 2>/dev/null || apt clean 2>/dev/null || true
        rm -rf /tmp/zabbix-* 2>/dev/null || true
        rm -rf /root/.ansible/tmp/* 2>/dev/null || true
      when: space_check.rc != 0

  tasks:
    # CentOS 7 安装
    - block:
        - name: Import Zabbix GPG key for CentOS 7
          rpm_key:
            key: https://repo.zabbix.com/RPM-GPG-KEY-ZABBIX-A14FE591
            state: present
            validate_certs: false

        - name: Check if Zabbix repo exists
          stat:
            path: /etc/yum.repos.d/zabbix.repo
          register: repo_exists_centos7

        - name: Install Zabbix repository for CentOS 7
          yum:
            name: https://repo.zabbix.com/zabbix/6.4/rhel/7/x86_64/zabbix-release-6.4-1.el7.noarch.rpm
            state: present
            validate_certs: false
          when: not repo_exists_centos7.stat.exists

        - name: Clean yum cache
          command: yum clean all
          changed_when: false

        - name: Install Zabbix Agent2
          yum:
            name: "{{ zabbix_agent_package }}"
            state: present
      when: system_type == "centos7"

    # Anolis 8 安装
    - block:
        - name: Import Zabbix GPG key for Anolis 8
          rpm_key:
            key: https://repo.zabbix.com/RPM-GPG-KEY-ZABBIX-A14FE591
            state: present
            validate_certs: false

        - name: Check if Zabbix repo exists
          stat:
            path: /etc/yum.repos.d/zabbix.repo
          register: repo_exists_anolis8

        - name: Download Zabbix repository package for Anolis 8
          get_url:
            url: https://repo.zabbix.com/zabbix/6.4/rhel/8/x86_64/zabbix-release-6.4-1.el8.noarch.rpm
            dest: /tmp/zabbix-release-6.4-1.el8.noarch.rpm
            mode: '0644'
            timeout: 30
            validate_certs: false
          when: not repo_exists_anolis8.stat.exists

        - name: Install Zabbix repository package manually
          command: rpm -Uvh /tmp/zabbix-release-6.4-1.el8.noarch.rpm
          register: repo_install
          failed_when: 
            - repo_install.rc != 0
            - "'已经安装' not in repo_install.stderr"
            - "'already installed' not in repo_install.stderr"
          when: not repo_exists_anolis8.stat.exists

        - name: Clean dnf cache
          command: dnf clean all
          changed_when: false

        - name: Install Zabbix Agent2
          dnf:
            name: "{{ zabbix_agent_package }}"
            state: present
      when: system_type == "anolis8"

    # Ubuntu 18.04 安装
    - block:
        - name: Import Zabbix GPG key for Ubuntu
          apt_key:
            url: https://repo.zabbix.com/zabbix-official-repo.key
            state: present

        - name: Check if Zabbix repo exists
          stat:
            path: /etc/apt/sources.list.d/zabbix.list
          register: repo_exists_ubuntu

        - name: Download Zabbix repository package for Ubuntu 18.04
          get_url:
            url: https://repo.zabbix.com/zabbix/6.4/ubuntu/pool/main/z/zabbix-release/zabbix-release_6.4-1+ubuntu18.04_all.deb
            dest: /tmp/zabbix-release.deb
            mode: '0644'
            timeout: 30
          when: not repo_exists_ubuntu.stat.exists

        - name: Install Zabbix repository
          apt:
            deb: /tmp/zabbix-release.deb
            state: present
          when: not repo_exists_ubuntu.stat.exists

        - name: Update apt cache
          apt:
            update_cache: yes

        - name: Install Zabbix Agent2
          apt:
            name: "{{ zabbix_agent_package }}"
            state: present
      when: system_type == "ubuntu18"

    # 通用配置步骤
    - 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: Configure Zabbix Agent2
      template:
        src: zabbix_agent2.conf.j2
        dest: "{{ zabbix_agent_config }}"
        owner: root
        group: root
        mode: '0644'
      notify: restart zabbix-agent2

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

    - name: Configure firewall for CentOS/RHEL systems
      firewalld:
        port: "10050/tcp"
        permanent: yes
        state: enabled
        immediate: yes
      when: system_type in ["centos7", "anolis8"]
      ignore_errors: yes

    - name: Configure firewall for Ubuntu systems
      ufw:
        rule: allow
        port: '10050'
        proto: tcp
      when: system_type == "ubuntu18"
      ignore_errors: yes

    - name: Verify Zabbix Agent2 is running
      systemd:
        name: "{{ zabbix_agent_service }}"
      register: service_status

    - name: Display service status
      debug:
        msg: "Zabbix Agent2 on {{ inventory_hostname }} is {{ service_status.status.ActiveState }}"

    - name: Test agent connectivity
      command: zabbix_agent2 -t agent.ping
      register: agent_test
      changed_when: false
      failed_when: false

    - name: Display connectivity test result
      debug:
        msg: "Agent test result: {{ agent_test.stdout if agent_test.rc == 0 else 'Failed: ' + agent_test.stderr }}"

  handlers:
    - name: restart zabbix-agent2
      systemd:
        name: "{{ zabbix_agent_service }}"
        state: restarted

  post_tasks:
    - name: Clean up downloaded files
      file:
        path: "{{ item }}"
        state: absent
      loop:
        - /tmp/zabbix-release-6.4-1.el8.noarch.rpm
        - /tmp/zabbix-release-6.4-1.el7.noarch.rpm
        - /tmp/zabbix-release.deb
      ignore_errors: yes

    - name: Final verification
      shell: |
        echo "=== Zabbix Agent2 Status ==="
        systemctl status zabbix-agent2 --no-pager -l || service zabbix-agent2 status
        echo ""
        echo "=== Network Test ==="
        ss -tlnp | grep 10050 || netstat -tlnp | grep 10050 || echo "Port 10050 not listening"
        echo ""
        echo "=== Version Info ==="
        zabbix_agent2 --version 2>/dev/null | head -1 || echo "Version check failed"
      register: final_check
      failed_when: false

    - name: Display final verification
      debug:
        var: final_check.stdout_lines
