---
- name: 移除 Docker 并安装 Podman - 新 Server 节点
  hosts: ash2e,ash1d,ch2
  become: yes
  gather_facts: no
  serial: 1  # 逐个节点处理，避免并发冲突
  
  tasks:
    - name: 显示当前处理的节点
      debug:
        msg: "🔧 正在处理节点: {{ inventory_hostname }}"

    - name: 检查 Docker 服务状态
      shell: systemctl is-active docker 2>/dev/null || echo "inactive"
      register: docker_status
      changed_when: false

    - name: 停止 Docker 服务
      systemd:
        name: docker
        state: stopped
        enabled: no
      ignore_errors: yes
      when: docker_status.stdout == "active"

    - name: 停止 Docker socket
      systemd:
        name: docker.socket
        state: stopped
        enabled: no
      ignore_errors: yes

    - name: 移除 Docker 相关包
      apt:
        name:
          - docker-ce
          - docker-ce-cli
          - containerd.io
          - docker-buildx-plugin
          - docker-compose-plugin
          - docker.io
          - docker-doc
          - docker-compose
          - docker-registry
          - containerd
          - runc
        state: absent
        purge: yes
      ignore_errors: yes

    - name: 清理 Docker 数据目录
      file:
        path: "{{ item }}"
        state: absent
      loop:
        - /var/lib/docker
        - /var/lib/containerd
        - /etc/docker
        - /etc/containerd
      ignore_errors: yes

    - name: 清理 Docker 用户组
      group:
        name: docker
        state: absent
      ignore_errors: yes

    - name: 更新包缓存
      apt:
        update_cache: yes
        cache_valid_time: 3600

    - name: 安装 Podman 及相关工具
      apt:
        name:
          - podman
          - buildah
          - skopeo
          - podman-compose
        state: present
      retries: 3
      delay: 10

    - name: 启用 Podman socket 服务
      systemd:
        name: podman.socket
        enabled: yes
        state: started
      ignore_errors: yes

    - name: 创建 Podman 用户服务目录
      file:
        path: /etc/systemd/user
        state: directory
        mode: '0755'

    - name: 验证 Podman 安装
      shell: podman --version
      register: podman_version
      
    - name: 验证 Podman Compose 安装
      shell: podman-compose --version 2>/dev/null || echo "未安装"
      register: podman_compose_version
      
    - name: 检查 Docker 清理状态
      shell: systemctl is-active docker 2>/dev/null || echo "已移除"
      register: final_docker_status
      
    - name: 显示节点处理结果
      debug:
        msg: |
          ✅ 节点 {{ inventory_hostname }} 处理完成
          🐳 Docker 状态: {{ final_docker_status.stdout }}
          📦 Podman 版本: {{ podman_version.stdout }}
          🔧 Compose 状态: {{ podman_compose_version.stdout }}

    - name: 清理 apt 缓存
      apt:
        autoclean: yes
        autoremove: yes