---
- name: Distribute Nomad Podman Driver to all nodes
  hosts: nomad_cluster
  become: yes
  vars:
    nomad_user: nomad
    nomad_data_dir: /opt/nomad/data
    nomad_plugins_dir: "{{ nomad_data_dir }}/plugins"

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

    - name: Create plugins directory
      file:
        path: "{{ nomad_plugins_dir }}"
        state: directory
        owner: "{{ nomad_user }}"
        group: "{{ nomad_user }}"
        mode: '0755'

    - name: Copy Nomad Podman driver from local
      copy:
        src: /tmp/nomad-driver-podman
        dest: "{{ nomad_plugins_dir }}/nomad-driver-podman"
        owner: "{{ nomad_user }}"
        group: "{{ nomad_user }}"
        mode: '0755'

    - name: Update Nomad configuration for plugin directory
      lineinfile:
        path: /etc/nomad.d/nomad.hcl
        regexp: '^plugin_dir'
        line: 'plugin_dir = "{{ nomad_plugins_dir }}"'
        insertafter: 'data_dir = "/opt/nomad/data"'

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

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

    - 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

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

    - name: Check driver status
      shell: |
        /usr/local/bin/nomad node status -self | grep -A 10 "Driver Status" || /usr/bin/nomad node status -self | grep -A 10 "Driver Status"
      register: driver_status
      failed_when: false

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