---

### tags:

- name: "Reading firewall entry for <{{ current_firewall_name }}>"
  set_fact:  
    firewall_record: "{{ firewall_records | selectattr('name', 'equalto', current_firewall_name) | list | first | default({'name': '-', 'id': '-'}) }}"
    firewall_template: "firewall-{{ current_firewall_name }}.json.j2"
  tags:
    - update_networks

- name: "Printing firewall entry for <{{ current_firewall_name }}>"
  debug:
    msg: "{{ firewall_record }}"
  when:
   - debug
  tags:
    - update_networks

- name: "Creating new firewall entry <{{ current_firewall_name }}>"
  uri:
    method: POST
    url: "https://api.hetzner.cloud/v1/firewalls"
    body_format: json
    body: "{{ lookup('template',firewall_template) }}"
    headers:
      accept: application/json
      authorization: Bearer {{ hetzner_authentication_ansible }}
    return_content: yes
    status_code: 201
  when: firewall_records | selectattr("name", "equalto", current_firewall_name) | list | length == 0
  delegate_to: 127.0.0.1
  become: false
  tags:
    - update_networks

# TODO port changes are not written corectly
- name: "Updating firewall entry <{{ current_firewall_name }}>"
  uri:
    method: PUT
    url: "https://api.hetzner.cloud/v1/firewalls/{{ firewall_record.id }}"
    body_format: json
    body: "{{ lookup('template',firewall_template) }}"
    headers:
      accept: application/json
      authorization: Bearer {{ hetzner_authentication_ansible }}
    return_content: yes
    status_code: 200
  when: firewall_records | selectattr("name", "equalto", current_firewall_name) | list | length == 1
  delegate_to: 127.0.0.1
  become: false
  tags:
    - update_networks
