---
- name: 安装并配置新的 Nomad Server 节点
  hosts: influxdb1
  become: yes
  gather_facts: no
  
  tasks:
    - name: 更新包缓存
      apt:
        update_cache: yes
        cache_valid_time: 3600
      retries: 3
      delay: 10

    - name: 安装依赖包
      apt:
        name:
          - wget
          - curl
          - unzip
          - podman
          - buildah
          - skopeo
        state: present
      retries: 3
      delay: 10

    - name: 检查 Nomad 是否已安装
      shell: which nomad || echo "not_found"
      register: nomad_check
      changed_when: false

    - name: 下载并安装 Nomad
      block:
        - name: 下载 Nomad 1.10.5
          get_url:
            url: "https://releases.hashicorp.com/nomad/1.10.5/nomad_1.10.5_linux_amd64.zip"
            dest: "/tmp/nomad.zip"
            mode: '0644'

        - name: 解压 Nomad
          unarchive:
            src: "/tmp/nomad.zip"
            dest: "/usr/bin/"
            remote_src: yes
            owner: root
            group: root
            mode: '0755'

        - name: 清理临时文件
          file:
            path: "/tmp/nomad.zip"
            state: absent
      when: nomad_check.stdout == "not_found"

    - name: 验证 Nomad 安装
      shell: nomad version
      register: nomad_version_output
      
    - name: 显示安装结果
      debug:
        msg: |
          ✅ 节点 {{ inventory_hostname }} 软件安装完成
          📦 Podman: {{ ansible_facts.packages.podman[0].version if ansible_facts.packages.podman is defined else 'checking...' }}
          🎯 Nomad: {{ nomad_version_output.stdout.split('\n')[0] }}

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

    - name: 继续完整配置
      debug:
        msg: "软件安装完成，现在将运行完整的 Nomad 配置..."