---
# showcase/remove-setup-nic.yml — Remove temporary internet NIC
#
# Removes the eth-setup device added by common.yml after package
# installation is complete. Uses the Incus PUT API to remove the device.
# Running containers return 202 (async), so we accept that and wait.

- name: Remove temporary incusbr0 NIC
  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
  register: instance_config

- name: Delete eth-setup device from instance
  ansible.builtin.uri:
    url: "{{ incus_api }}/1.0/instances/{{ ffsdn_instance_name }}"
    method: PUT
    client_cert: "{{ incus_cert }}"
    client_key: "{{ incus_key }}"
    validate_certs: false
    body_format: json
    body: >-
      {{
        instance_config.json.metadata
        | combine({
            'devices': instance_config.json.metadata.devices
                       | dict2items
                       | rejectattr('key', 'equalto', 'eth-setup')
                       | items2dict
          })
      }}
    status_code: [200, 202]
    return_content: true
    headers:
      If-Match: "{{ instance_config.headers.etag | default('') }}"
  register: nic_remove_result
  when: "'eth-setup' in instance_config.json.metadata.devices"

- name: Wait for device removal to complete
  ansible.builtin.uri:
    url: "{{ incus_api }}{{ nic_remove_result.json.operation }}/wait?timeout=30"
    method: GET
    client_cert: "{{ incus_cert }}"
    client_key: "{{ incus_key }}"
    validate_certs: false
    return_content: true
  when:
    - nic_remove_result is defined
    - nic_remove_result.status | default(200) == 202

- name: Clean up eth1 network config inside container
  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/rm", "-f", "/etc/systemd/network/80-eth1.network", "/tmp/activate-eth1.sh"]
      record-output: false
      interactive: false
      wait-for-websocket: false
    status_code: [202]
  ignore_errors: true
