---

- name: "Read DNS entry for {{ record_name }}.{{ domain }} from digitalocean"
  uri:
    url: "https://api.digitalocean.com/v2/domains/{{ domain }}/records?name={{ record_name }}.{{ domain }}"
    headers:
      accept: application/json
      authorization: Bearer {{ digitalocean_authentication_token }}
    return_content: yes
  register: domain_records_response
  delegate_to: 127.0.0.1
  become: false
  tags:
    - update_dns

- name: "Save DNS entry as variable (fact)"
  set_fact: 
    domain_records_response_json: "{{ domain_records_response.json }}"
  delegate_to: 127.0.0.1
  become: false
  tags:
    - update_dns

- name: "Parse DNS entry for {{ record_name }}.{{ domain }}"
  set_fact:  
    domain_record: "{{ domain_records_response_json.domain_records | json_query(jmesquery) | first | default({'name': '-', 'ip': '-'}) }}"
  vars:
    jmesquery: '[*].{id: id, name: name, ip: data}'
  delegate_to: 127.0.0.1
  become: false
  tags:
    - update_dns

- name: "Print DNS entry for {{ record_name }}.{{ domain }}"
  debug:
    msg: "{{ domain_record }}"
  delegate_to: 127.0.0.1
  become: false
  tags:
    - update_dns

- name: "Delete DNS entry for <{{ record_data }}:{{ record_name }}> if necessary"
  uri:
    method: DELETE
    url: "https://api.digitalocean.com/v2/domains/{{ domain }}/records/{{ domain_record.id }}"
    headers:
      authorization: Bearer {{ digitalocean_authentication_token }}
    return_content: yes
    status_code: 204
  when:
    - domain_record.ip != '-'
    - record_data != domain_record.ip
  delegate_to: 127.0.0.1
  become: false
  tags:
    - update_dns

- name: "Create DNS entry for <{{ record_name }}> if necessary"
  uri:
    method: POST
    url: "https://api.digitalocean.com/v2/domains/{{ domain }}/records"
    headers:
      authorization: Bearer {{ digitalocean_authentication_token }}
    body: '{{ create_record | to_json }}'
    body_format: json
    return_content: yes
    status_code: 201
  vars:
    create_record:
        type: 'A'
        ttl: "{{ sma_digitalocean_ttl | default(1800) }}"
        data: "{{ record_data }}"
        name: "{{ record_name }}"
  when:
        domain_record.ip == '-'
    or record_data != domain_record.ip
    or record_name != domain_record.name
  delegate_to: 127.0.0.1
  become: false
  tags:
    - update_dns
