---
- name: Fix CentOS 7 pcre2 dependency and remove zabbix-agent
  hosts: centos7
  gather_facts: yes
  become: yes
  vars:
    # pcre2库文件包的路径（与run.sh同级目录）
    pcre2_package: "./pcre2-libs.tar.gz"

  tasks:
    - name: Check if this is a CentOS 7 system that needs fixing
      debug:
        msg: "Processing {{ inventory_hostname }}"

    - block:
        - name: Stop zabbix-agent service if running
          systemd:
            name: zabbix-agent
            state: stopped
          ignore_errors: yes

        - name: Disable zabbix-agent service
          systemd:
            name: zabbix-agent
            enabled: no
          ignore_errors: yes

        - name: Get list of installed zabbix packages
          shell: rpm -qa | grep zabbix
          register: zabbix_packages
          ignore_errors: yes

        - name: Display packages to be removed
          debug:
            msg: "Found zabbix packages: {{ zabbix_packages.stdout_lines }}"
          when: zabbix_packages.stdout_lines | length > 0

        - name: Remove all zabbix packages (keep user and configs)
          shell: |
            for pkg in $(rpm -qa | grep zabbix); do
              echo "Removing package: $pkg"
              rpm -e --nodeps $pkg
            done
          register: removal_result
          ignore_errors: yes
          when: zabbix_packages.stdout_lines | length > 0

        - name: Display removal results
          debug:
            var: removal_result.stdout_lines
          when: removal_result is defined and removal_result.stdout_lines is defined

        - name: Check if pcre2 libraries already exist
          stat:
            path: /usr/lib64/libpcre2-8.so.0
          register: pcre2_exists

        - name: Display pcre2 status
          debug:
            msg: "pcre2 libraries {{ 'already exist' if pcre2_exists.stat.exists else 'need to be installed' }}"

        - name: Copy pcre2 package to target machine
          copy:
            src: "{{ pcre2_package }}"
            dest: /tmp/pcre2-libs.tar.gz
            mode: '0644'
          when: not pcre2_exists.stat.exists

        - name: Extract pcre2 libraries
          shell: |
            cd /tmp
            tar -xzf pcre2-libs.tar.gz
            echo "Extracted files:"
            ls -la libpcre2*
          register: extract_result
          when: not pcre2_exists.stat.exists

        - name: Display extract results
          debug:
            var: extract_result.stdout_lines
          when: extract_result is defined

        - name: Install pcre2 libraries
          shell: |
            cd /tmp
            
            echo "Installing pcre2 libraries..."
            
            # 复制库文件到系统目录
            cp libpcre2-8.so.0 /usr/lib64/
            cp libpcre2-8.so.0.5.0 /usr/lib64/
            cp libpcre2-posix.so.1 /usr/lib64/
            cp libpcre2-posix.so.1.0.1 /usr/lib64/
            
            # 设置正确的权限
            chmod 755 /usr/lib64/libpcre2*
            chown root:root /usr/lib64/libpcre2*
            
            # 更新库缓存
            ldconfig 2>&1 || true
            
            echo "pcre2 libraries installed successfully"
            
            # 显示安装的文件
            echo "Installed pcre2 files:"
            ls -la /usr/lib64/libpcre2*
          register: pcre2_install_result
          when: not pcre2_exists.stat.exists

        - name: Display pcre2 installation result
          debug:
            var: pcre2_install_result.stdout_lines
          when: pcre2_install_result is defined

        - name: Verify pcre2 installation
          shell: |
            echo "=== pcre2库文件验证 ==="
            find /usr/lib64 -name "*pcre2*" 2>/dev/null | sort
            echo ""
            echo "=== 库缓存验证 ==="
            ldconfig -p | grep pcre2 | head -5 || echo "No pcre2 found in cache yet"
            echo ""
            echo "=== 检查 /lib64 中的链接 ==="
            ls -la /lib64/libpcre2* 2>/dev/null || echo "No pcre2 links in /lib64"
          register: pcre2_verification

        - name: Display pcre2 verification
          debug:
            var: pcre2_verification.stdout_lines

        - name: Clean up temporary pcre2 files
          file:
            path: "{{ item }}"
            state: absent
          loop:
            - /tmp/pcre2-libs.tar.gz
            - /tmp/libpcre2-8.so.0
            - /tmp/libpcre2-8.so.0.5.0
            - /tmp/libpcre2-posix.so.1
            - /tmp/libpcre2-posix.so.1.0.1
          ignore_errors: yes

        - name: Test if zabbix_agentd would work now (if it exists)
          shell: |
            if [ -f "/usr/sbin/zabbix_agentd" ]; then
              echo "Testing zabbix_agentd dependencies..."
              ldd /usr/sbin/zabbix_agentd | grep pcre2 || echo "No zabbix_agentd found or pcre2 dependency not resolved"
            else
              echo "zabbix_agentd not found (already removed)"
            fi
          register: zabbix_deps_test
          ignore_errors: yes

        - name: Display dependency test result
          debug:
            var: zabbix_deps_test.stdout_lines

        - name: Check remaining zabbix artifacts
          shell: |
            echo "=== 检查剩余的zabbix相关文件 ==="
            echo "RPM packages:"
            rpm -qa | grep zabbix || echo "No zabbix packages found"
            echo ""
            echo "Service files:"
            ls -la /usr/lib/systemd/system/*zabbix* 2>/dev/null || echo "No zabbix service files found"
            echo ""
            echo "Binary files:"
            ls -la /usr/sbin/zabbix* 2>/dev/null || echo "No zabbix binaries found"
            echo ""
            echo "Configuration directories:"
            ls -la /etc/zabbix/ 2>/dev/null || echo "No /etc/zabbix directory"
            echo ""
            echo "Zabbix user status:"
            id zabbix 2>/dev/null || echo "Zabbix user not found"
          register: cleanup_verification

        - name: Display cleanup verification
          debug:
            var: cleanup_verification.stdout_lines

        - name: Final status summary
          debug:
            msg:
              - "=== 操作完成总结 ==="
              - "1. Zabbix RPM packages removed: {{ 'Yes' if zabbix_packages.stdout_lines | length > 0 else 'None found' }}"
              - "2. pcre2 libraries installed: {{ 'Yes' if not pcre2_exists.stat.exists else 'Already existed' }}"
              - "3. Zabbix user preserved: Yes (not touched)"
              - "4. System ready for custom zabbix installation"

      rescue:
        - name: Display error information
          debug:
            msg: "An error occurred during the process on {{ inventory_hostname }}"

        - name: Show failed task details
          debug:
            var: ansible_failed_result
          when: ansible_failed_result is defined

        - name: Continue with partial cleanup if possible
          debug:
            msg: "Attempting to continue with available operations..."
