---
- name: Fix ch4 Nomad configuration - convert from server to client
  hosts: ch4
  become: yes
  vars:
    ansible_host: 100.117.106.136
  
  tasks:
    - name: Backup current Nomad config
      copy:
        src: /etc/nomad.d/nomad.hcl
        dest: /etc/nomad.d/nomad.hcl.backup
        remote_src: yes
        backup: yes

    - name: Update Nomad config to client mode
      blockinfile:
        path: /etc/nomad.d/nomad.hcl
        marker: "# {mark} ANSIBLE MANAGED CLIENT CONFIG"
        block: |
          server {
            enabled = false
          }

          client {
            enabled = true
            network_interface = "tailscale0"
            
            servers = [
              "semaphore.tailnet-68f9.ts.net:4647",
              "ash1d.tailnet-68f9.ts.net:4647",
              "ash2e.tailnet-68f9.ts.net:4647",
              "ch2.tailnet-68f9.ts.net:4647",
              "ch3.tailnet-68f9.ts.net:4647",
              "onecloud1.tailnet-68f9.ts.net:4647",
              "de.tailnet-68f9.ts.net:4647"
            ]
            
            meta {
              consul = "true"
              consul_version = "1.21.5"
              consul_server = "true"
            }
          }
        insertbefore: '^server \{'
        replace: '^server \{.*?\}'

    - name: Update client block
      blockinfile:
        path: /etc/nomad.d/nomad.hcl
        marker: "# {mark} ANSIBLE MANAGED CLIENT BLOCK"
        block: |
          client {
            enabled = true
            network_interface = "tailscale0"
            
            servers = [
              "semaphore.tailnet-68f9.ts.net:4647",
              "ash1d.tailnet-68f9.ts.net:4647",
              "ash2e.tailnet-68f9.ts.net:4647",
              "ch2.tailnet-68f9.ts.net:4647",
              "ch3.tailnet-68f9.ts.net:4647",
              "onecloud1.tailnet-68f9.ts.net:4647",
              "de.tailnet-68f9.ts.net:4647"
            ]
            
            meta {
              consul = "true"
              consul_version = "1.21.5"
              consul_server = "true"
            }
          }
        insertbefore: '^client \{'
        replace: '^client \{.*?\}'

    - name: Restart Nomad service
      systemd:
        name: nomad
        state: restarted
        enabled: yes

    - name: Wait for Nomad to be ready
      wait_for:
        port: 4646
        host: "{{ ansible_default_ipv4.address }}"
        delay: 5
        timeout: 30

    - name: Verify Nomad client status
      shell: |
        NOMAD_ADDR=http://localhost:4646 nomad node status | grep -q "ready"
      register: nomad_ready
      failed_when: nomad_ready.rc != 0
      retries: 3
      delay: 10

    - name: Display completion message
      debug:
        msg: |
          ✅ Successfully converted ch4 from Nomad server to client
          ✅ Nomad service restarted
          ✅ Configuration updated

