---
- name: Configure Nomad Podman Driver
  hosts: target_nodes
  become: yes
  tasks:
    - name: Create backup directory
      file:
        path: /etc/nomad.d/backup
        state: directory
        mode: '0755'
    
    - name: Backup current nomad.hcl
      copy:
        src: /etc/nomad.d/nomad.hcl
        dest: "/etc/nomad.d/backup/nomad.hcl.bak.{{ ansible_date_time.iso8601 }}"
        remote_src: yes
    
    - name: Create plugin directory
      file:
        path: /opt/nomad/plugins
        state: directory
        owner: nomad
        group: nomad
        mode: '0755'
    
    - name: Create symlink for podman driver
      file:
        src: /usr/bin/nomad-driver-podman
        dest: /opt/nomad/plugins/nomad-driver-podman
        state: link
    
    - name: Copy podman driver configuration
      copy:
        src: ../../files/podman-driver.hcl
        dest: /etc/nomad.d/podman-driver.hcl
        owner: root
        group: root
        mode: '0644'
    
    - name: Remove existing plugin_dir configuration
      lineinfile:
        path: /etc/nomad.d/nomad.hcl
        regexp: '^plugin_dir = "/opt/nomad/data/plugins"'
        state: absent

    - name: Configure Nomad to use Podman driver
      blockinfile:
        path: /etc/nomad.d/nomad.hcl
        marker: "# {mark} ANSIBLE MANAGED BLOCK - PODMAN DRIVER"
        block: |
          plugin_dir = "/opt/nomad/plugins"

          plugin "podman" {
            config {
              volumes {
                enabled = true
              }
              logging {
                type = "journald"
              }
              gc {
                container = true
              }
            }
          }
      register: nomad_config_result
    
    - name: Restart nomad service
      systemd:
        name: nomad
        state: restarted
        enabled: yes
    
    - name: Wait for nomad to start
      wait_for:
        port: 4646
        delay: 10
        timeout: 60
    
    - name: Check nomad status
      command: nomad node status
      register: nomad_status
      changed_when: false
    
    - name: Display nomad status
      debug:
        var: nomad_status.stdout_lines