---
- name: 测试将 Podman 切换到 Snap 版本 (ch2 节点)
  hosts: ch2
  become: yes
  gather_facts: yes

  tasks:
    - name: 检查当前 Podman 版本和安装方式
      shell: |
        echo "=== 当前 Podman 信息 ==="
        podman --version
        echo "安装路径: $(which podman)"
        echo "=== Snap 状态 ==="
        which snap || echo "snap 未安装"
        snap list podman 2>/dev/null || echo "Podman snap 未安装"
        echo "=== 包管理器状态 ==="
        dpkg -l | grep podman || echo "未通过 apt 安装"
      register: current_status

    - name: 显示当前状态
      debug:
        msg: "{{ current_status.stdout }}"

    - name: 检查 snap 是否已安装
      shell: which snap
      register: snap_check
      ignore_errors: yes
      changed_when: false

    - name: 安装 snapd (如果未安装)
      apt:
        name: snapd
        state: present
      when: snap_check.rc != 0

    - name: 确保 snapd 服务运行
      systemd:
        name: snapd
        state: started
        enabled: yes

    - name: 检查当前 Podman snap 版本
      shell: snap info podman
      register: snap_podman_info
      ignore_errors: yes

    - name: 显示可用的 Podman snap 版本
      debug:
        msg: "{{ snap_podman_info.stdout if snap_podman_info.rc == 0 else '无法获取 snap podman 信息' }}"

    - name: 停止当前 Podman 相关服务
      systemd:
        name: podman
        state: stopped
      ignore_errors: yes

    - name: 移除通过包管理器安装的 Podman
      apt:
        name: podman
        state: absent
        purge: yes
      ignore_errors: yes

    - name: 安装 Podman snap (edge 通道)
      snap:
        name: podman
        state: present
        classic: yes
        channel: edge

    - name: 创建符号链接 (确保 podman 命令可用)
      file:
        src: /snap/bin/podman
        dest: /usr/local/bin/podman
        state: link
        force: yes

    - name: 验证 Snap Podman 安装
      shell: |
        /snap/bin/podman --version
        which podman
      register: snap_podman_verify

    - name: 显示安装结果
      debug:
        msg: |
          ✅ Snap Podman 安装完成
          🚀 版本: {{ snap_podman_verify.stdout_lines[0] }}
          📍 路径: {{ snap_podman_verify.stdout_lines[1] }}

    - name: 测试 Podman 基本功能
      shell: |
        /snap/bin/podman version
        /snap/bin/podman info --format json | jq -r '.host.arch'
      register: podman_test
      ignore_errors: yes

    - name: 显示测试结果
      debug:
        msg: "Podman 测试结果: {{ podman_test.stdout if podman_test.rc == 0 else '测试失败' }}"