---
- name: Migrate Nomad from Docker to Podman (Simple Version)
  hosts: all
  become: yes
  vars:
    nomad_user: nomad
    nomad_config_dir: /etc/nomad.d
    nomad_config_file: "{{ nomad_config_dir }}/nomad.hcl"

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

    - name: Backup current Nomad configuration
      copy:
        src: "{{ nomad_config_file }}"
        dest: "{{ nomad_config_file }}.backup-{{ ansible_date_time.epoch }}"
        remote_src: yes

    - name: Get nomad user info
      getent:
        database: passwd
        key: "{{ nomad_user }}"
      register: nomad_user_info

    - name: Set nomad user UID variable
      set_fact:
        nomad_uid: "{{ nomad_user_info.ansible_facts.getent_passwd[nomad_user][1] }}"

    - name: Enable lingering for nomad user
      command: loginctl enable-linger {{ nomad_user }}
      failed_when: false

    - name: Create runtime directory for nomad user
      file:
        path: "/run/user/{{ nomad_uid }}"
        state: directory
        owner: "{{ nomad_user }}"
        group: "{{ nomad_user }}"
        mode: '0700'

    - name: Start Podman socket as nomad user
      shell: |
        sudo -u {{ nomad_user }} XDG_RUNTIME_DIR=/run/user/{{ nomad_uid }} systemctl --user enable --now podman.socket
      args:
        creates: "/run/user/{{ nomad_uid }}/podman/podman.sock"

    - name: Create new Nomad configuration with Podman
      copy:
        content: |
          datacenter = "dc1"
          region = "global"
          data_dir = "/opt/nomad/data"

          bind_addr = "0.0.0.0"

          client {
            enabled = true
            servers = [
              "100.116.158.95:4647",
            ]
          }

          # Docker plugin (disabled)
          # plugin "docker" {
          #   config {
          #     allow_privileged = true
          #     volumes {
          #       enabled = true
          #     }
          #   }
          # }

          plugin "podman" {
            config {
              socket_path = "unix:///run/user/{{ nomad_uid }}/podman/podman.sock"
              volumes {
                enabled = true
              }
            }
          }

          consul {
            address = "127.0.0.1:8500"
          }
        dest: "{{ nomad_config_file }}"
        owner: root
        group: root
        mode: '0644'

    - name: Update Nomad systemd service to run as nomad user
      copy:
        content: |
          [Unit]
          Description=Nomad
          Documentation=https://www.nomadproject.io/
          Requires=network-online.target
          After=network-online.target
          Wants=network-online.target

          [Service]
          Type=notify
          User={{ nomad_user }}
          Group={{ nomad_user }}
          ExecReload=/bin/kill -HUP $MAINPID
          ExecStart=/usr/local/bin/nomad agent -config={{ nomad_config_dir }}
          KillMode=process
          Restart=on-failure
          LimitNOFILE=65536
          Environment=XDG_RUNTIME_DIR=/run/user/{{ nomad_uid }}

          [Install]
          WantedBy=multi-user.target
        dest: /etc/systemd/system/nomad.service
        owner: root
        group: root
        mode: '0644'

    - name: Reload systemd daemon
      systemd:
        daemon_reload: yes

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

    - name: Wait for Nomad to be ready (local check)
      wait_for:
        port: 4646
        host: localhost
        delay: 5
        timeout: 60

    - name: Verify Nomad is running
      shell: systemctl is-active nomad
      register: nomad_status

    - name: Display Nomad status
      debug:
        msg: "Nomad service status: {{ nomad_status.stdout }}"

    - name: Check Podman socket
      stat:
        path: "/run/user/{{ nomad_uid }}/podman/podman.sock"
      register: podman_socket

    - name: Display Podman socket status
      debug:
        msg: "Podman socket exists: {{ podman_socket.stat.exists }}"

    - name: Test Podman as nomad user
      shell: |
        sudo -u {{ nomad_user }} XDG_RUNTIME_DIR=/run/user/{{ nomad_uid }} podman version --format json
      register: podman_test
      failed_when: false

    - name: Display Podman test result
      debug:
        msg: |
          Podman test: {{ 'SUCCESS' if podman_test.rc == 0 else 'FAILED' }}
          {% if podman_test.rc != 0 %}
          Error: {{ podman_test.stderr }}
          {% endif %}