---
- name: Fix HCP1 and HCP2 Podman Configuration
  hosts: hcp1,hcp2
  become: yes
  tasks:
    - name: Stop Nomad service
      systemd:
        name: nomad
        state: stopped

    - name: Ensure nomad user exists
      user:
        name: nomad
        system: yes
        shell: /bin/false
        home: /home/nomad
        create_home: yes

    - name: Ensure Podman socket is running
      systemd:
        name: podman.socket
        state: started
        enabled: yes

    - name: Set proper permissions on Podman socket
      file:
        path: /run/podman/podman.sock
        mode: '0666'
      ignore_errors: yes

    - name: Create nomad data directory
      file:
        path: /opt/nomad/data
        state: directory
        owner: nomad
        group: nomad
        mode: '0755'

    - name: Create nomad log directory
      file:
        path: /var/log/nomad
        state: directory
        owner: nomad
        group: nomad
        mode: '0755'

    - 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

    - name: Validate Nomad configuration
      shell: /usr/local/bin/nomad config validate /etc/nomad.d/nomad.hcl
      register: config_validation
      failed_when: false

    - name: Display configuration validation
      debug:
        var: config_validation

    - 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: Check Nomad node status
      shell: /usr/local/bin/nomad node status -self
      register: node_status
      failed_when: false

    - name: Display node status
      debug:
        var: node_status.stdout_lines