---
- name: Fix Nomad Podman Driver Configuration
  hosts: all
  become: yes
  vars:
    nomad_user: nomad

  tasks:
    - name: Stop Nomad service
      systemd:
        name: nomad
        state: stopped

    - name: Update Nomad configuration to properly reference Podman plugin
      replace:
        path: /etc/nomad.d/nomad.hcl
        regexp: 'plugin "podman" \{\n  config \{\n    socket_path = "unix:///run/user/1001/podman/podman.sock"\n    volumes \{\n      enabled = true\n    \}\n  \}\n\}'
        replace: |
          plugin "nomad-driver-podman" {
            config {
              socket_path = "unix:///run/user/1001/podman/podman.sock"
              volumes {
                enabled = true
              }
            }
          }

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

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

    - name: Wait for plugins to load
      pause:
        seconds: 15

    - name: Check if Podman driver is now loaded
      shell: |
        sudo -u {{ nomad_user }} /usr/local/bin/nomad node status -self | grep -A 20 "Driver Status"
      register: driver_status

    - name: Display driver status
      debug:
        var: driver_status.stdout_lines

    - name: Check Nomad logs for successful plugin loading
      shell: journalctl -u nomad -n 20 --no-pager | grep -E "(podman|plugin)"
      register: recent_logs
      failed_when: false

    - name: Display recent plugin logs
      debug:
        var: recent_logs.stdout_lines

    - name: Final verification - Test Podman functionality
      shell: |
        sudo -u {{ nomad_user }} /usr/local/bin/nomad node status -json | jq -r '.Drivers | keys[]' | grep -i podman
      register: podman_driver_check
      failed_when: false

    - name: Display final result
      debug:
        msg: |
          Podman driver status: {{ 'SUCCESS - Driver loaded!' if 'podman' in (podman_driver_check.stdout | default('')) else 'Still checking...' }}
          Available drivers: {{ podman_driver_check.stdout_lines | default(['none']) | join(', ') }}