---
- name: PVE Web Interface Fix
  hosts: pve
  gather_facts: yes
  tasks:
    - name: Check PVE web service status
      systemd:
        name: pveproxy
        state: started
      register: pveproxy_status

    - name: Display PVE proxy status
      debug:
        msg: "PVE Proxy Status: {{ pveproxy_status.status.ActiveState }}"

    - name: Check if port 8006 is listening
      wait_for:
        port: 8006
        host: "{{ ansible_default_ipv4.address }}"
        timeout: 5
      register: port_check
      ignore_errors: yes

    - name: Display port status
      debug:
        msg: "Port 8006: {{ 'OPEN' if port_check.rc == 0 else 'CLOSED' }}"

    - name: Restart PVE proxy service
      systemd:
        name: pveproxy
        state: restarted
      register: restart_result

    - name: Display restart result
      debug:
        msg: "PVE Proxy restarted: {{ restart_result.changed }}"

    - name: Wait for service to be ready
      wait_for:
        port: 8006
        host: "{{ ansible_default_ipv4.address }}"
        timeout: 30

    - name: Test local web access
      uri:
        url: "https://localhost:8006"
        method: GET
        validate_certs: no
        timeout: 10
      register: local_test
      ignore_errors: yes

    - name: Display local test result
      debug:
        msg: "Local web access: {{ 'SUCCESS' if local_test.status == 200 else 'FAILED' }}"

    - name: Test external web access
      uri:
        url: "https://{{ ansible_default_ipv4.address }}:8006"
        method: GET
        validate_certs: no
        timeout: 10
      register: external_test
      ignore_errors: yes

    - name: Display external test result
      debug:
        msg: "External web access: {{ 'SUCCESS' if external_test.status == 200 else 'FAILED' }}"

    - name: Test Tailscale web access
      uri:
        url: "https://{{ inventory_hostname }}:8006"
        method: GET
        validate_certs: no
        timeout: 10
      register: tailscale_test
      ignore_errors: yes

    - name: Display Tailscale test result
      debug:
        msg: "Tailscale web access: {{ 'SUCCESS' if tailscale_test.status == 200 else 'FAILED' }}"

    - name: Check PVE logs for errors
      command: journalctl -u pveproxy -n 10 --no-pager
      register: pve_logs
      ignore_errors: yes

    - name: Display PVE logs
      debug:
        msg: "{{ pve_logs.stdout_lines }}"
      when: pve_logs.rc == 0

    - name: Check system logs for network errors
      command: journalctl -n 20 --no-pager | grep -i "route\|network\|connection\|error"
      register: system_logs
      ignore_errors: yes

    - name: Display system logs
      debug:
        msg: "{{ system_logs.stdout_lines }}"
      when: system_logs.rc == 0
