---
# decommission.yml — Runs before Aether deletes an instance
#
# Aether passes the same ffsdn_ extra vars as post-deploy:
#   ffsdn_instance_name, ffsdn_instance_ip, ffsdn_cluster_id,
#   ffsdn_cluster_name, ffsdn_deployed_by
#
# This playbook runs best-effort: failures do NOT block instance
# deletion in Aether. Uses the Incus REST API for all operations
# (no SSH needed).

- name: Decommission — graceful shutdown and logging
  hosts: localhost
  gather_facts: false
  connection: local

  vars:
    incus_api: "https://192.168.102.140:8443"
    # AWX runner mounts project at /runner/project/ during job execution
    incus_cert: "/runner/project/incus-client.crt"
    incus_key: "/runner/project/incus-client.key"

  tasks:
    - name: Check if instance 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
      when: ffsdn_instance_name is defined

    - name: Stop application services (best-effort)
      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 list-units --type=service --state=running --no-legend \
                | awk '{print $1}' \
                | grep -vE '^(ssh|systemd|dbus|cron|networking|rsyslog)' \
                | head -20 \
                | xargs -r -n1 systemctl stop 2>/dev/null || true
              journalctl --flush 2>/dev/null || true
          record-output: false
          interactive: false
          wait-for-websocket: false
        status_code: [202]
      ignore_errors: true
      when:
        - instance_check is defined
        - instance_check.status == 200
        - instance_check.json.metadata.status is defined
        - instance_check.json.metadata.status == "Running"

    - name: Record decommission in ledger
      ansible.builtin.lineinfile:
        path: /tmp/awx-deploy-ledger.log
        line: >-
          {{ lookup('pipe', 'date -Iseconds') }}
          DECOMMISSION instance={{ ffsdn_instance_name | default('unknown') }}
          ip={{ ffsdn_instance_ip | default('') }}
          cluster={{ ffsdn_cluster_name | default('unknown') }}
          deployed_by={{ ffsdn_deployed_by | default('unknown') }}
          status=completed
        create: true
        mode: "0644"
