---
# showcase/decommission/webapp-web.yml — Graceful nginx shutdown + ACL cleanup
#
# Stops nginx and removes this web instance's ACL rule from the db ACL.
# Best-effort: failures do not block instance deletion.

- name: Stop nginx gracefully
  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"
        - |
          systemctl stop nginx 2>/dev/null || true
          systemctl stop php*-fpm 2>/dev/null || true
      record-output: false
      interactive: false
      wait-for-websocket: false
    status_code: [202]
  ignore_errors: true

# --- Clean up ACL rule from db (best-effort) ---

- name: Discover database instances for ACL cleanup
  ansible.builtin.include_tasks: showcase/helpers.yml
  vars:
    discovery_prefix: "webapp-db-"
  ignore_errors: true

- name: Remove ACL rule from db
  when:
    - discovered_siblings is defined
    - discovered_siblings | length > 0
  block:
    - name: Build db ACL name for cleanup
      ansible.builtin.set_fact:
        db_acl_name: "52-{{ discovered_siblings[0].name }}-aether-acl"

    - name: Read current db ACL for cleanup
      ansible.builtin.uri:
        url: "{{ incus_api }}/1.0/network-acls/{{ db_acl_name }}"
        method: GET
        client_cert: "{{ incus_cert }}"
        client_key: "{{ incus_key }}"
        validate_certs: false
        return_content: true
        status_code: [200, 404]
      register: db_acl_cleanup

    - name: Filter out this instance's ACL rules
      ansible.builtin.set_fact:
        cleaned_ingress: >-
          {{ db_acl_cleanup.json.metadata.ingress | default([])
             | rejectattr('description', 'search', ffsdn_instance_name)
             | list }}
      when: db_acl_cleanup.status == 200

    - name: Update db ACL (remove this web instance's rule)
      ansible.builtin.uri:
        url: "{{ incus_api }}/1.0/network-acls/{{ db_acl_name }}"
        method: PATCH
        client_cert: "{{ incus_cert }}"
        client_key: "{{ incus_key }}"
        validate_certs: false
        body_format: json
        body:
          ingress: "{{ cleaned_ingress }}"
        status_code: [200]
      when:
        - db_acl_cleanup.status == 200
        - cleaned_ingress is defined
  ignore_errors: true

- name: Report web decommission
  ansible.builtin.debug:
    msg: "Web instance {{ ffsdn_instance_name }} decommissioned (nginx stopped, ACL cleaned)"
