---
- name: Final Podman Permission Fix for Nomad
  hosts: all
  become: yes
  tasks:
    - name: Stop Nomad service
      systemd:
        name: nomad
        state: stopped

    - name: Install podman for nomad user (system-wide)
      package:
        name: podman
        state: present

    - name: Enable podman socket for nomad user
      systemd:
        name: podman.socket
        enabled: yes
        state: started
        scope: system
        daemon_reload: yes

    - name: Create nomad user podman configuration directory
      file:
        path: /home/nomad/.config/containers
        state: directory
        owner: nomad
        group: nomad
        mode: '0755'
        recurse: yes

    - name: Configure podman for nomad user to use system socket
      copy:
        content: |
          [containers]
          
          [engine]
          remote = true
          
          [service_destinations]
          [service_destinations.system]
          uri = "unix:///run/podman/podman.sock"
        dest: /home/nomad/.config/containers/containers.conf
        owner: nomad
        group: nomad
        mode: '0644'

    - name: Update Nomad configuration to use system podman socket
      replace:
        path: /etc/nomad.d/nomad.hcl
        regexp: 'socket_path = "unix:///run/user/1001/podman/podman.sock"'
        replace: 'socket_path = "unix:///run/podman/podman.sock"'

    - name: Add nomad user to necessary groups
      user:
        name: nomad
        groups: 
          - podman
        append: yes

    - name: Create podman group if it doesn't exist
      group:
        name: podman
        state: present

    - name: Set proper permissions on system podman socket directory
      file:
        path: /run/podman
        state: directory
        mode: '0755'
        group: podman

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

    - name: Wait for Nomad to be ready
      wait_for:
        port: 4646
        timeout: 60

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

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

    - name: Display final driver status
      debug:
        var: final_driver_status.stdout_lines

    - name: Test podman access for nomad user
      shell: sudo -u nomad podman version
      register: podman_test
      failed_when: false

    - name: Display podman test result
      debug:
        var: podman_test.stdout_lines