- name: "Create ssh key"
  delegate_to: localhost
  community.digitalocean.digital_ocean_sshkey:
    oauth_token: "{{ digitalocean_authentication_token }}"
    name: "{{ item }}"
    ssh_pub_key: "{{ lookup('file', 'users/' + item + '/ssh.pub') }}"
    state: present
  register: result
  loop: '{{ smardigo_plattform_users }}'

- name: "Get fingerprints for ssh_keys"
  delegate_to: localhost
  community.digitalocean.digital_ocean_sshkey_info:
    oauth_token: "{{ digitalocean_authentication_token }}"
  register: do_sshkeys_found

- name: "Combine default droplet config with settings vor inventory_hostname"
  set_fact:
    droplet_combined: "{{ droplet_defaults | combine(droplet) }}"

- block:
  - name: "Creating tag names by RegEx on droplet name"
    set_fact:
      tag_service: "{{ droplet.name | regex_search('[a-z]+-([a-z]+)-[0-9]+','\\1') | first | string }}" 
      tag_stage: "{{ droplet.name | regex_search('([a-z]+)-[a-z]+-[0-9]+','\\1') | first | string }}"

  - name: "Create new droplet"
    delegate_to: localhost
    community.digitalocean.digital_ocean_droplet:
      oauth_token: "{{ digitalocean_authentication_token }}"
      state: "{{ droplet_combined.state | default('present') }}"
      name: "{{ droplet_combined.name }}"
      size: "{{ droplet_combined.size }}"
      region: "{{ droplet_combined.region }}"
      image: "{{ droplet_combined.image }}"
      wait_timeout: "{{ droplet_combined.wait_timeout | default(500) }}"
      unique_name: "{{ droplet_combined.unique_name | default(True) }}"
      ssh_keys: "{{ do_sshkeys_found.data | json_query(querystring) }}"
    register: new_droplet
    vars:
      querystring: "[*].fingerprint"
    
  - name: "Tag new server"
    delegate_to: localhost
    community.digitalocean.digital_ocean_tag:
      oauth_token: "{{ digitalocean_authentication_token }}"
      name: "{{ item | replace('-','_') }}"
      resource_id: "{{ new_droplet.data.droplet.id }}"
      state: present
    register: tag_response
    loop: "{{ droplet.tags }}"

  - name: "Set server_ip by fact parsing"
    delegate_to: localhost
    set_fact:
      stage_server_ip: "{{ item }}"
    loop: "{{ new_droplet.data | community.general.json_query(jsonquery_ipaddress) }}"
    vars:
      jsonquery_ipaddress: "droplet.networks.v4[?type=='public'].ip_address"
  
# TODO: abolish _digitalocean/tasks/domain.yml
  - name: "Create dns record for droplet"
    delegate_to: localhost
    community.digitalocean.digital_ocean_domain_record:
      oauth_token: "{{ digitalocean_authentication_token }}"
      state: present
      domain: "{{ domain }}"
      type: A
      name: "{{ new_droplet.data.droplet.name }}"
      data: "{{ stage_server_ip }}"
      force_update: yes
