---
- name: 部署韩国节点Nomad配置
  hosts: ch2,ch3
  become: yes
  gather_facts: no
  vars:
    nomad_config_dir: "/etc/nomad.d"
    nomad_config_file: "{{ nomad_config_dir }}/nomad.hcl"
    source_config_dir: "/root/mgmt/infrastructure/configs/server"
    
  tasks:
    - name: 获取主机名短名称（去掉后缀）
      set_fact:
        short_hostname: "{{ inventory_hostname | regex_replace('\\$', '') }}"

    - name: 确保 Nomad 配置目录存在
      file:
        path: "{{ nomad_config_dir }}"
        state: directory
        owner: root
        group: root
        mode: '0755'

    - name: 部署 Nomad 配置文件到韩国节点
      copy:
        src: "{{ source_config_dir }}/nomad-{{ short_hostname }}.hcl"
        dest: "{{ nomad_config_file }}"
        owner: root
        group: root
        mode: '0644'
        backup: yes
      notify: restart nomad

    - name: 检查 Nomad 二进制文件位置
      shell: which nomad || find /usr -name nomad 2>/dev/null | head -1
      register: nomad_binary_path
      failed_when: nomad_binary_path.stdout == ""

    - name: 创建/更新 Nomad systemd 服务文件
      copy:
        dest: "/etc/systemd/system/nomad.service"
        owner: root
        group: root
        mode: '0644'
        content: |
          [Unit]
          Description=Nomad
          Documentation=https://www.nomadproject.io/
          Requires=network-online.target
          After=network-online.target
          
          [Service]
          Type=notify
          User=root
          Group=root
          ExecStart={{ nomad_binary_path.stdout }} agent -config=/etc/nomad.d/nomad.hcl
          ExecReload=/bin/kill -HUP $MAINPID
          KillMode=process
          Restart=on-failure
          LimitNOFILE=65536
          
          [Install]
          WantedBy=multi-user.target
      notify: restart nomad

    - name: 确保 Nomad 数据目录存在
      file:
        path: "/opt/nomad/data"
        state: directory
        owner: root
        group: root
        mode: '0755'

    - name: 重新加载 systemd daemon
      systemd:
        daemon_reload: yes

    - name: 启用并启动 Nomad 服务
      systemd:
        name: nomad
        enabled: yes
        state: started

    - name: 等待 Nomad 服务启动
      wait_for:
        port: 4646
        host: "{{ ansible_host }}"
        delay: 5
        timeout: 30
      ignore_errors: yes

    - name: 显示 Nomad 服务状态
      command: systemctl status nomad
      register: nomad_status
      changed_when: false

    - name: 显示 Nomad 服务状态信息
      debug:
        var: nomad_status.stdout_lines

  handlers:
    - name: restart nomad
      systemd:
        name: nomad
        state: restarted