---
- name: Fix Nomad Cluster Configuration
  hosts: nomad_servers
  become: yes
  vars:
    nomad_servers_list:
      - "100.116.158.95"  # semaphore
      - "100.103.147.94"  # ash2e
      - "100.81.26.3"     # ash1d
      - "100.90.159.68"   # ch2
      - "{{ ansible_default_ipv4.address }}"  # ch3 (will be determined dynamically)
  
  tasks:
    - name: Stop Nomad service
      systemd:
        name: nomad
        state: stopped
      ignore_errors: yes

    - name: Create nomad user
      user:
        name: nomad
        system: yes
        shell: /bin/false
        home: /opt/nomad
        create_home: no

    - name: Create Nomad configuration directory
      file:
        path: /etc/nomad.d
        state: directory
        mode: '0755'

    - name: Create Nomad data directory
      file:
        path: /opt/nomad/data
        state: directory
        mode: '0755'
        owner: nomad
        group: nomad
      ignore_errors: yes

    - name: Create Nomad log directory
      file:
        path: /var/log/nomad
        state: directory
        mode: '0755'
        owner: nomad
        group: nomad
      ignore_errors: yes

    - name: Generate Nomad server configuration
      template:
        src: nomad-server.hcl.j2
        dest: /etc/nomad.d/nomad.hcl
        mode: '0644'
      notify: restart nomad

    - name: Create Nomad systemd service file
      copy:
        content: |
          [Unit]
          Description=Nomad
          Documentation=https://www.nomadproject.io/
          Requires=network-online.target
          After=network-online.target
          ConditionFileNotEmpty=/etc/nomad.d/nomad.hcl

          [Service]
          Type=notify
          User=nomad
          Group=nomad
          ExecStart=/usr/bin/nomad agent -config=/etc/nomad.d/nomad.hcl
          ExecReload=/bin/kill -HUP $MAINPID
          KillMode=process
          Restart=on-failure
          LimitNOFILE=65536

          [Install]
          WantedBy=multi-user.target
        dest: /etc/systemd/system/nomad.service
        mode: '0644'

    - name: Reload systemd daemon
      systemd:
        daemon_reload: yes

    - name: Enable and start Nomad service
      systemd:
        name: nomad
        enabled: yes
        state: started

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