---
- name: Clean up Consul configuration from dedicated clients
  hosts: hcp1,influxdb1,browser
  become: yes
  
  tasks:
    - name: Stop Consul service
      systemd:
        name: consul
        state: stopped
        enabled: no

    - name: Disable Consul service
      systemd:
        name: consul
        enabled: no

    - name: Kill any remaining Consul processes
      shell: |
        pkill -f consul || true
        sleep 2
        pkill -9 -f consul || true
      ignore_errors: yes

    - name: Remove Consul systemd service file
      file:
        path: /etc/systemd/system/consul.service
        state: absent

    - name: Remove Consul configuration directory
      file:
        path: /etc/consul.d
        state: absent

    - name: Remove Consul data directory
      file:
        path: /opt/consul
        state: absent

    - name: Reload systemd daemon
      systemd:
        daemon_reload: yes

    - name: Verify Consul is stopped
      shell: |
        if pgrep -f consul; then
          echo "Consul still running"
          exit 1
        else
          echo "Consul stopped successfully"
        fi
      register: consul_status
      failed_when: consul_status.rc != 0

    - name: Display cleanup status
      debug:
        msg: "Consul cleanup completed on {{ inventory_hostname }}"
