---
# showcase/decommission/webapp-instance.yml — Per-instance decommission for webapp
#
# Called from webapp-decommission.yml in a loop over ffsdn_instances.
# The 'instance' loop var has: name, ip, component_name, image_alias, type
# Routes to webapp-db.yml or webapp-web.yml based on component_name.

- name: Set instance facts from loop variable
  ansible.builtin.set_fact:
    ffsdn_instance_name: "{{ instance.name }}"
    component_name: "{{ instance.component_name }}"

- name: "Check if {{ ffsdn_instance_name }} still exists"
  ansible.builtin.uri:
    url: "{{ incus_api }}/1.0/instances/{{ ffsdn_instance_name }}"
    method: GET
    client_cert: "{{ incus_cert }}"
    client_key: "{{ incus_key }}"
    validate_certs: false
    return_content: true
    status_code: [200, 404]
  register: instance_check

- name: "Route to component-specific decommission for {{ ffsdn_instance_name }}"
  ansible.builtin.include_tasks: "webapp-{{ component_name }}.yml"
  when:
    - instance_check.status == 200
    - component_name in decommission_tasks
    - instance_check.json.metadata.status | default('') == "Running"
  ignore_errors: true

- name: Record decommission in ledger
  ansible.builtin.lineinfile:
    path: /tmp/awx-deploy-ledger.log
    line: >-
      {{ lookup('pipe', 'date -Iseconds') }}
      SHOWCASE-DECOMMISSION instance={{ ffsdn_instance_name }}
      blueprint=webapp component={{ component_name | default('unknown') }}
      status=completed
    create: true
    mode: "0644"
  when: instance_check.status == 200
