---
# showcase/decommission/webapp-db.yml — Graceful MariaDB shutdown
#
# Best-effort: failures do not block instance deletion.

- name: Stop MariaDB 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"
        - |
          echo "Stopping MariaDB gracefully..."
          systemctl stop mariadb 2>/dev/null || true
          echo "MariaDB stopped"
      record-output: true
      interactive: false
      wait-for-websocket: false
    status_code: [202]
    return_content: true
  register: db_stop_exec
  ignore_errors: true

- name: Wait for MariaDB stop (up to 30s)
  ansible.builtin.uri:
    url: "{{ incus_api }}{{ db_stop_exec.json.operation }}/wait?timeout=30"
    method: GET
    client_cert: "{{ incus_cert }}"
    client_key: "{{ incus_key }}"
    validate_certs: false
    return_content: true
  ignore_errors: true
  when: db_stop_exec is not failed

- name: Report MariaDB decommission
  ansible.builtin.debug:
    msg: "MariaDB on {{ ffsdn_instance_name }} stopped gracefully"
