---
- name: Configure Podman for Nomad Integration
  hosts: all
  become: yes
  gather_facts: yes

  tasks:
    - name: 显示当前处理的节点
      debug:
        msg: "🔧 正在为 Nomad 配置 Podman: {{ inventory_hostname }}"

    - name: 确保 Podman 已安装
      package:
        name: podman
        state: present

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

    - name: 创建 Podman 系统配置目录
      file:
        path: /etc/containers
        state: directory
        mode: '0755'

    - name: 配置 Podman 使用系统 socket
      copy:
        content: |
          [engine]
          # 使用系统级 socket 而不是用户级 socket
          active_service = "system"
          [engine.service_destinations]
          [engine.service_destinations.system]
          uri = "unix:///run/podman/podman.sock"
        dest: /etc/containers/containers.conf
        mode: '0644'

    - name: 检查是否存在 nomad 用户
      getent:
        database: passwd
        key: nomad
      register: nomad_user_check
      ignore_errors: yes

    - name: 为 nomad 用户创建配置目录
      file:
        path: "/home/nomad/.config/containers"
        state: directory
        owner: nomad
        group: nomad
        mode: '0755'
      when: nomad_user_check is succeeded

    - name: 为 nomad 用户配置 Podman
      copy:
        content: |
          [engine]
          active_service = "system"
          [engine.service_destinations]
          [engine.service_destinations.system]
          uri = "unix:///run/podman/podman.sock"
        dest: /home/nomad/.config/containers/containers.conf
        owner: nomad
        group: nomad
        mode: '0644'
      when: nomad_user_check is succeeded

    - name: 将 nomad 用户添加到 podman 组
      user:
        name: nomad
        groups: podman
        append: yes
      when: nomad_user_check is succeeded
      ignore_errors: yes

    - name: 创建 podman 组（如果不存在）
      group:
        name: podman
        state: present
      ignore_errors: yes

    - name: 设置 podman socket 目录权限
      file:
        path: /run/podman
        state: directory
        mode: '0755'
        group: podman
      ignore_errors: yes

    - name: 验证 Podman socket 权限
      file:
        path: /run/podman/podman.sock
        mode: '066'
      when: nomad_user_check is succeeded
      ignore_errors: yes

    - name: 验证 Podman 安装
      shell: podman --version
      register: podman_version

    - name: 测试 Podman 功能
      shell: podman info
      register: podman_info
      ignore_errors: yes

    - name: 显示配置结果
      debug:
        msg: |
          ✅ 节点 {{ inventory_hostname }} Podman 配置完成
          📦 Podman 版本: {{ podman_version.stdout }}
          🐳 Podman 状态: {{ 'SUCCESS' if podman_info.rc == 0 else 'WARNING' }}
          👤 Nomad 用户: {{ 'FOUND' if nomad_user_check is succeeded else 'NOT FOUND' }}