---
- name: "Block to handle hetzner server state in case of problems"
  block:
  - name: "Increment the retry count"
    set_fact:
      retry_count: "{{ retry_count | default(0) | int + 1 }}"

  - name: "Checking state for server <{{ inventory_hostname }}> is <{{ server_state }}>"
    hetzner.hcloud.hcloud_server:
      api_token: "{{ hetzner_authentication_ansible }}"
      name: "{{ inventory_hostname }}"
      server_type: "{{ hetzner_server_type }}"
      image: "{{ hetzner_server_image }}"
      ssh_keys: "{{ hetzner_ssh_keys }}"
      labels: "{{ hetzner_server_labels }}"
      location: nbg1
      state: "{{ server_state }}"
    delegate_to: 127.0.0.1
    become: false
    async: 300
    poll: 5
    register: hcloud_response
    ignore_errors: yes

  - name: "Block - DEBUG: hcloud_response"
    debug:
      msg: '{{ hcloud_response.msg }}'
    when:
      - hcloud_response.msg is defined

  - name: "Ensure Server is STARTED when server_state=present"
    hetzner.hcloud.hcloud_server:
      api_token: "{{ hetzner_authentication_ansible }}"
      name: "{{ inventory_hostname }}"
      state: "started"
    delegate_to: 127.0.0.1
    become: false
    async: 150
    poll: 15
    register: hcloud_response
    when:
      - server_state == 'present'

  rescue:
    - name: "RESCUE - fail: Maximum retries reached"
      fail:
        msg: "max_retries of {{ max_retries }} reached. Plz check."
      when: retry_count | int == max_retries | int

    - name: "RESCUE-fail DEBUG: hcloud_response"
      debug:
        msg: '{{ hcloud_response.msg }}'

    - name: "RESCUE: wait_for {{ retry_delay }} sec. between retries"
      wait_for:
        timeout: "{{ retry_delay }}"
      delegate_to: localhost
      become: false

    - name: "Include _set_server one time again => increase retry_count"
      include_tasks: _set_server_state.yml
