---

#############################################################
#   Reading server infos from hetzner rest api
#############################################################

- name: "Reading hetzner server infos for stage <{{ stage }}/{{ stage_kube }}>"
  uri:
    url: "https://api.hetzner.cloud/v1/servers?label_selector=stage={{ stage }}"
    method: GET
    headers:
      authorization: Bearer {{ hetzner_authentication_ansible }}
  register: hetzner_servers_result
  delegate_to: 127.0.0.1
  tags:
    - always

- name: "Setting hetzner server pagination count: <{{ hetzner_servers_result.json.meta.pagination.last_page }}>"
  set_fact:
    total_server_pages: "{{ hetzner_servers_result.json.meta.pagination.last_page }}"
  tags:
    - always

- name: "Reading hetzner server infos for stage <{{ stage }}/{{ stage_kube }}> without pagination"
  set_fact:
    hetzner_servers: "{{ hetzner_servers_result.json.servers }}"
  tags:
    - always
  when:
    - total_server_pages == '1'

- name: "Block << WITH >> pagination"
  block:
  - name: "Reading hetzner server infos for stage <{{ stage }}/{{ stage_kube }}> with pagination"
    uri:
      url: "https://api.hetzner.cloud/v1/servers?label_selector=stage={{ stage }}&page={{ item }}"
      method: GET
      headers:
        authorization: Bearer {{ hetzner_authentication_ansible }}
    register: hetzner_servers_results
    with_sequence: start=1 end={{ total_server_pages }}
    delegate_to: 127.0.0.1

  - name: "Reading hetzner server infos for stage <{{ stage }}/{{ stage_kube }}> without pagination"
    set_fact:
      hetzner_servers: "{{ hetzner_servers_results.results | json_query(querystr1) | first | json_query(querystr2) | json_query(querystr2) }}"
    vars:
      querystr1: "[[*].json.servers]"
      querystr2: "[]"
  when:
    - total_server_pages != '1'
  tags:
    - always

- name: "Printing hetzner server infos for stage <{{ stage }}/{{ stage_kube }}>"
  debug:
    msg: "{{ hetzner_servers }}"
  tags:
    - always
  when:
    - debug

#############################################################
#   Reading network infos from hetzner rest api
#############################################################

- name: "Reading hetzner private network infos for stage <{{ stage }}/{{ stage_kube }}>"
  uri:
    url: "https://api.hetzner.cloud/v1/networks?label_selector=stage={{ stage }}"
    method: GET
    headers:
      authorization: Bearer {{ hetzner_authentication_ansible }}
  register: hetzner_networks
  delegate_to: 127.0.0.1
  tags:
    - always

- name: "Printing hetzner private network infos for stage <{{ stage }}/{{ stage_kube }}>"
  debug:
    msg: "{{ hetzner_networks.json.networks }}"
  tags:
    - always
  when:
    - debug

- name: "Reading hetzner private network id for <{{ stage }}/{{ stage_kube }}>"
  set_fact:
    stage_network_id: "{{ hetzner_networks.json.networks | map(attribute='id') | first | default(0) }}"
  tags:
    - always

#############################################################
#   Reading loadbalancer infos from hetzner rest api
#############################################################

- name: "Reading hetzner loadbalancer infos for stage <{{ stage }}/{{ stage_kube }}>"
  uri:
    url: "https://api.hetzner.cloud/v1/load_balancers"
    method: GET
    headers:
      authorization: Bearer {{ hetzner_authentication_ansible }}
  register: hetzner_loadbalancers
  delegate_to: 127.0.0.1
  tags:
    - always

- name: "Printing hetzner loadbalancer infos for stage <{{ stage }}/{{ stage_kube }}>"
  debug:
    msg: "{{ hetzner_loadbalancers.json.load_balancers }}"
  tags:
    - always
  when:
    - debug

- name: "Reading hetzner loadbalancer infos for stage <{{ stage }}/{{ stage_kube }}>"
  set_fact:
    shared_service_kube_loadbalancer_private_ip: "{{
       hetzner_loadbalancers.json.load_balancers
       | json_query(querystr1)
       | first
       | default([])
       | first
       | default(shared_service_kube_loadbalancer_private_ip_not_available) }}"
    shared_service_kube_loadbalancer_public_ip: "{{
       hetzner_loadbalancers.json.load_balancers
       | json_query(querystr2)
       | first
       | default(shared_service_kube_loadbalancer_public_ip_not_available) }}"
  vars:
    querystr1: "[?name=='{{ stage_kube_load_balancer }}'].private_net[*].ip"
    querystr2: "[?name=='{{ stage_kube_load_balancer }}'].public_net.ipv4.ip"
  tags:
    - always

- name: "Reading hetzner loadbalancer infos for stage <{{ stage }}/{{ stage_kube }}>" # noqa var-naming
  set_fact:
    "stage_public_{{ item.name | replace(stage_kube + '-', '') | replace('-','_') }}_loadbalancer_ip": "{{ item.public_net.ipv4.ip }}"
    "stage_private_{{ item.name | replace(stage_kube + '-', '') | replace('-','_') }}_loadbalancer_ip": "{{ item.private_net[0].ip if item.private_net | length > 0 else 'Not Available' }}"
  loop: "{{ hetzner_loadbalancers.json.load_balancers | selectattr('name', 'match', '^' + stage_kube + '-.*') | list }}"
  loop_control:
    label: "{{ item.name }}"
  tags:
    - always

#############################################################
#   Setting stage infos as facts
#############################################################

# due to a hetzner api bug for label selector: only last given selector is used - label_selector=stage=XXX,!manual not working correctly
- name: "Reading hetzner server infos for stage <{{ stage }}/{{ stage_kube }}>"
  set_fact:
    stage_server_infos: "\
      {% set stage_server_infos = [] %}\
      {% for server in hetzner_servers %}\
        {% if server.labels.manual is not defined %}\
          {% set stage_server_info={'public_ip': server.public_net.ipv4.ip, 'name': server.name, 'id': server.id} %}\
          {% for label in (server.labels | dict2items) %}\
            {% set x=stage_server_info.__setitem__(label.key,label.value) %}\
          {% endfor %}\
          {% set x=stage_server_info.__setitem__('private_ip','-') %}\
          {% if (server.private_net|length) > 0 %}\
            {% for private_net in server.private_net %}\
              {% if private_net.network == stage_network_id|int %}\
                {% set x=stage_server_info.__setitem__('private_ip',private_net.ip) %}\
              {% endif %}\
            {% endfor %}\
          {% endif %}\
          {{ stage_server_infos.append(stage_server_info) }}\
        {% endif %}\
      {% endfor %}\
      {{ stage_server_infos | list | sort(attribute='name') }}"
  tags:
    - always

- name: "Printing hetzner server infos for stage <{{ stage }}/{{ stage_kube }}>"
  debug:
    msg: "{{ stage_server_infos }}"
  tags:
    - always
  when:
    - debug

- name: "Reading stage infos for stage <{{ stage }}/{{ stage_kube }}>"
  set_fact:
    stage_server_id: "{{ stage_server_infos | json_query(querystr1) | first | default('') }}"
    stage_server_ip: "{{ stage_server_infos | json_query(querystr2) | first | default('') }}"
    stage_private_server_ip: "{{ stage_server_infos | json_query(querystr3) | first | default('') }}"
  vars:
    querystr1: "[?name=='{{ inventory_hostname }}'].id"
    querystr2: "[?name=='{{ inventory_hostname }}'].public_ip"
    querystr3: "[?name=='{{ inventory_hostname }}'].private_ip"
  tags:
    - always

- name: "Printing autodicoverd values for <{{ inventory_hostname }}> on stage <{{ stage }}/{{ stage_kube }}>"
  debug:
    msg:
      - "host: <{{ inventory_hostname }}>"
      - "server id: <{{ stage_server_id }}>"
      - "server ip (public): <{{ stage_server_ip }}>"
      - "server ip (private): <{{ stage_private_server_ip }}>"
      - "server groups: <{{ group_names | join(',') }}>"
      - "network id: <{{ stage_network_id }}>"
      - "ingess public ip: <{{ shared_service_kube_loadbalancer_public_ip }}>"
      - "ingess private ip: <{{ shared_service_kube_loadbalancer_public_ip }}>"
      - "logstash public ip: <{{ shared_service_loadbalancer_logstash_public_ip }}>"
      - "logstash private ip: <{{ shared_service_loadbalancer_logstash_private_ip }}>"
      - "server info: <{{ stage_server_infos | selectattr('name', 'equalto', inventory_hostname) | default({}) }}>"
  tags:
    - always
