---
- name: Fix Nomad server configuration
  hosts: nomad_servers
  become: yes
  tasks:
    - name: Stop Nomad service
      systemd:
        name: nomad
        state: stopped

    - name: Backup current configuration
      copy:
        src: /etc/nomad.d/nomad.hcl
        dest: /etc/nomad.d/nomad.hcl.backup-server-fix
        remote_src: yes

    - name: Create clean server configuration
      copy:
        content: |
          datacenter = "{{ nomad_datacenter }}"
          region = "{{ nomad_region }}"
          data_dir = "/opt/nomad/data"
          bind_addr = "{{ ansible_default_ipv4.address }}"

          server {
            enabled = true
            bootstrap_expect = {{ nomad_bootstrap_expect }}
            encrypt = "{{ nomad_encrypt_key }}"
            
            retry_join = [
              "100.116.158.95",
              "100.103.147.94", 
              "100.81.26.3",
              "100.90.159.68",
              "100.86.141.112"
            ]
          }

          client {
            enabled = true
          }

          ui {
            enabled = true
          }

          addresses {
            http = "0.0.0.0"
            rpc = "{{ ansible_default_ipv4.address }}"
            serf = "{{ ansible_default_ipv4.address }}"
          }

          ports {
            http = 4646
            rpc = 4647
            serf = 4648
          }

          plugin "podman" {
            config {
              socket_path = "unix:///run/podman/podman.sock"
              volumes {
                enabled = true
              }
              recover_stopped = true
            }
          }

          consul {
            auto_advertise = false
            server_auto_join = false
            client_auto_join = false
          }

          log_level = "INFO"
          log_file = "/var/log/nomad/nomad.log"
        dest: /etc/nomad.d/nomad.hcl
        owner: nomad
        group: nomad
        mode: '0640'

    - name: Ensure Podman is installed
      package:
        name: podman
        state: present

    - name: Enable and start Podman socket
      systemd:
        name: podman.socket
        enabled: yes
        state: started

    - name: Validate Nomad configuration
      shell: /usr/local/bin/nomad config validate /etc/nomad.d/nomad.hcl || /usr/bin/nomad config validate /etc/nomad.d/nomad.hcl
      register: config_validation
      failed_when: config_validation.rc != 0

    - name: Start Nomad service
      systemd:
        name: nomad
        state: started
        enabled: yes

    - name: Wait for Nomad to be ready
      wait_for:
        port: 4646
        host: localhost
        delay: 10
        timeout: 60