---
- name: 升级 Podman 到最新版本 (warden 节点测试)
  hosts: warden
  become: yes
  gather_facts: yes

  tasks:
    - name: 检查当前 Podman 版本
      shell: podman --version
      register: current_podman_version
      ignore_errors: yes

    - name: 显示当前版本
      debug:
        msg: "当前 Podman 版本: {{ current_podman_version.stdout if current_podman_version.rc == 0 else '未安装或无法获取' }}"

    - name: 备份现有 Podman 配置
      shell: |
        if [ -d /etc/containers ]; then
          cp -r /etc/containers /etc/containers.backup.$(date +%Y%m%d)
        fi
        if [ -d /usr/share/containers ]; then
          cp -r /usr/share/containers /usr/share/containers.backup.$(date +%Y%m%d)
        fi
      ignore_errors: yes

    - name: 添加 Kubic 仓库 (HTTP 跳过签名)
      shell: |
        # 添加仓库并跳过签名验证
        echo "deb [trusted=yes] http://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable/xUbuntu_22.04/ /" > /etc/apt/sources.list.d/kubic-containers.list

    - name: 更新包列表 (跳过签名验证)
      shell: apt-get update -o Acquire::AllowInsecureRepositories=true -o Acquire::AllowDowngradeToInsecureRepositories=true

    - name: 检查仓库中可用的 Podman 版本
      shell: apt-cache policy podman
      register: podman_versions

    - name: 显示可用的 Podman 版本
      debug:
        msg: "{{ podman_versions.stdout }}"

    - name: 安装 Podman 5.x (强制跳过签名)
      shell: apt-get install -y --allow-unauthenticated --allow-downgrades --allow-remove-essential --allow-change-held-packages podman

    - name: 验证 Podman 5.x 安装
      shell: |
        podman --version
        podman info --format json | jq -r '.Version.Version'
      register: podman_5_verify

    - name: 显示升级结果
      debug:
        msg: |
          ✅ Podman 升级完成
          🚀 新版本: {{ podman_5_verify.stdout_lines[0] }}
          📊 详细版本: {{ podman_5_verify.stdout_lines[1] }}

    - name: 测试基本功能
      shell: |
        podman run --rm hello-world
      register: podman_test
      ignore_errors: yes

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

    - name: 检查相关服务状态
      shell: |
        systemctl status podman.socket 2>/dev/null || echo "podman.socket 未运行"
        systemctl status containerd 2>/dev/null || echo "containerd 未运行"
      register: service_status

    - name: 显示服务状态
      debug:
        msg: "{{ service_status.stdout }}"