---
# showcase/decommission/staticsite-instance.yml — Per-instance decommission for staticsite
#
# Called from staticsite-decommission.yml in a loop over ffsdn_instances.
# The 'instance' loop var has: name, ip, component_name, image_alias, type
# No special cleanup needed — just stop nginx gracefully.

- 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: "Stop nginx gracefully on {{ ffsdn_instance_name }}"
  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"
      record-output: false
      interactive: false
      wait-for-websocket: false
    status_code: [202]
  ignore_errors: true
  when:
    - instance_check.status == 200
    - instance_check.json.metadata.status | default('') == "Running"

- 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=staticsite component={{ component_name }}
      status=completed
    create: true
    mode: "0644"
  when: instance_check.status == 200
