---
# showcase/webapp-deploy-instance.yml — Per-instance tasks for webapp
#
# Called from webapp-post-deploy.yml in a loop over ffsdn_instances.
# The 'instance' loop var has: name, ip, component_name, image_alias, type
# Dispatches 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 }}"
    ffsdn_instance_ip: "{{ instance.ip | default('') }}"
    component_name: "{{ instance.component_name }}"

- name: "Wait for {{ ffsdn_instance_name }} to be running (up to 60s)"
  ansible.builtin.uri:
    url: "{{ incus_api }}/1.0/instances/{{ ffsdn_instance_name }}/state"
    method: GET
    client_cert: "{{ incus_cert }}"
    client_key: "{{ incus_key }}"
    validate_certs: false
    return_content: true
  register: instance_state
  until: instance_state.json.metadata.status == "Running"
  retries: 12
  delay: 5

- name: Validate component
  ansible.builtin.assert:
    that:
      - component_name in valid_components
    fail_msg: >-
      Unknown component '{{ component_name }}' for webapp blueprint.
      Instance '{{ ffsdn_instance_name }}' component must be one of: {{ valid_components | join(', ') }}.

- name: Display dispatch info
  ansible.builtin.debug:
    msg: "Webapp {{ component_name }} — configuring {{ ffsdn_instance_name }}"

- name: Run common setup tasks
  ansible.builtin.include_tasks: common.yml

- name: Route to component-specific tasks
  ansible.builtin.include_tasks: "webapp-{{ component_name }}.yml"

- name: Remove temporary internet NIC
  ansible.builtin.include_tasks: remove-setup-nic.yml

- name: Record deployment in ledger
  ansible.builtin.lineinfile:
    path: /tmp/awx-deploy-ledger.log
    line: >-
      {{ lookup('pipe', 'date -Iseconds') }}
      SHOWCASE-DEPLOY instance={{ ffsdn_instance_name }}
      blueprint=webapp component={{ component_name }}
      ip={{ ffsdn_instance_ip }}
      cluster={{ ffsdn_cluster_name | default('unknown') }}
      status=success
    create: true
    mode: "0644"
