---

### tags:
###   update_dns
###   update_networks

- name: "Checking state of server for <{{ inventory_hostname }}>"
  include_role:
    name: hcloud
    tasks_from: _set_server_state

- name: "Gathering current server infos from hetzner"
  hcloud_server_info:
    api_token: "{{ hetzner_authentication_ansible }}"
  register: hetzner_server_infos
  delegate_to: 127.0.0.1
  become: false
  tags:
    - update_dns
    - update_networks

- name: "Setting current server infos as fact: hetzner_server_infos_json"
  set_fact: 
    hetzner_server_infos_json: "{{ hetzner_server_infos.hcloud_server_info }}"
  delegate_to: 127.0.0.1
  become: false
  tags:
    - update_dns
    - update_networks

- name: "Reading ip address for {{ inventory_hostname }}"
  set_fact:
    stage_server_ip: "{{ hetzner_server_infos_json | json_query(querystr) | first }}"
  vars:
    querystr: "[?name=='{{ inventory_hostname }}'].ipv4_address"
  delegate_to: 127.0.0.1
  become: false
  tags:
    - update_dns
    - update_networks

- name: "Printing ip address for {{ inventory_hostname }}"
  debug:
    msg: "{{ stage_server_ip }}"
  delegate_to: 127.0.0.1
  become: false
  tags:
    - update_dns
    - update_networks
  when:
   - debug

#- name: "Checking present state for firewalls"
#  include_tasks: configure-firewall.yml
#  vars:
#    current_firewall_name: '{{ current_firewall }}'
#  with_items:
#    - 'default'
#    - 'kibana'
#    - 'monitoring'
#  loop_control:
#    loop_var: current_firewall
#  tags:
#    - update_networks

- name: "Checking present state for networks"
  include_tasks: configure-network.yml
  vars:
    current_network_name: '{{ current_network.name }}'
    current_network_labels: 'stage={{ stage }}'
    current_server_label_selector: '{{ current_network.label_selector }}'
  with_items: [
    {
      "name": "{{ stage }}",
      "label_selector": "stage={{ stage }}",
    }
  ]
  loop_control:
    loop_var: current_network
  tags:
    - update_networks

- name: "Checking present state of dns for {{ inventory_hostname }}"
  include_role:
    name: sma_digitalocean
    tasks_from: domain
  vars:
    record_data: "{{ stage_server_ip }}"
    record_name: "{{ inventory_hostname }}"
  tags:
    - update_dns

# needed due to some weird hetzner behaviour that some servers need more time to be well provisioned
- name: "Wait for {{ inventory_hostname }}"
  delegate_to: localhost
  wait_for:
    timeout: 180
    port: 22
    host: '{{ stage_server_ip }}'
    search_regex: OpenSSH
