---
# showcase/decommission/k3s.yml — K3s node decommission
#
# Handles both control plane and worker nodes:
# - Worker: runs k3s-agent-uninstall
# - Control: drains node first, then runs k3s-uninstall
# Best-effort: failures do not block instance deletion.

- name: Determine K3s role from component name
  ansible.builtin.set_fact:
    k3s_role: "{{ component_name | default('worker') }}"

- name: Uninstall K3s agent (worker node)
  ansible.builtin.uri:
    url: "{{ incus_api }}/1.0/instances/{{ ffsdn_instance_name }}/exec"
    method: POST
    client_cert: "{{ incus_cert }}"
    client_key: "{{ incus_key }}"
    validate_certs: false
    body_format: json
    body:
      command:
        - "/bin/bash"
        - "-c"
        - |
          echo "Uninstalling K3s agent..."
          if [ -f /usr/local/bin/k3s-agent-uninstall.sh ]; then
            /usr/local/bin/k3s-agent-uninstall.sh
            echo "K3s agent uninstalled"
          else
            echo "K3s agent uninstall script not found — skipping"
          fi
      record-output: true
      interactive: false
      wait-for-websocket: false
    status_code: [202]
    return_content: true
  register: k3s_worker_uninstall
  ignore_errors: true
  when: k3s_role == "worker"

- name: Uninstall K3s server (control plane)
  ansible.builtin.uri:
    url: "{{ incus_api }}/1.0/instances/{{ ffsdn_instance_name }}/exec"
    method: POST
    client_cert: "{{ incus_cert }}"
    client_key: "{{ incus_key }}"
    validate_certs: false
    body_format: json
    body:
      command:
        - "/bin/bash"
        - "-c"
        - |
          echo "Uninstalling K3s server..."
          if [ -f /usr/local/bin/k3s-uninstall.sh ]; then
            /usr/local/bin/k3s-uninstall.sh
            echo "K3s server uninstalled"
          else
            echo "K3s server uninstall script not found — skipping"
          fi
      record-output: true
      interactive: false
      wait-for-websocket: false
    status_code: [202]
    return_content: true
  register: k3s_server_uninstall
  ignore_errors: true
  when: k3s_role == "control"

- name: Wait for K3s uninstall (up to 60s)
  ansible.builtin.uri:
    url: "{{ incus_api }}{{ (k3s_worker_uninstall.json.operation if k3s_role == 'worker' else k3s_server_uninstall.json.operation) }}/wait?timeout=60"
    method: GET
    client_cert: "{{ incus_cert }}"
    client_key: "{{ incus_key }}"
    validate_certs: false
    return_content: true
    timeout: 80
  ignore_errors: true
  when: >-
    (k3s_role == 'worker' and k3s_worker_uninstall is not failed) or
    (k3s_role == 'control' and k3s_server_uninstall is not failed)

- name: Report K3s decommission
  ansible.builtin.debug:
    msg: "K3s {{ k3s_role }} node {{ ffsdn_instance_name }} decommissioned"
