---

- name: Set dns server for docker
  set_fact:
    docker_dns_servers: "{{ dns_servers }}"

- name: Show docker_dns_servers
  debug:
    msg: "{{ docker_dns_servers }}"

- name: Add upstream dns servers
  set_fact:
    docker_dns_servers: "{{ docker_dns_servers + upstream_dns_servers | default([]) }}"
  when: dns_mode in ['coredns', 'coredns_dual']

- name: Add global searchdomains
  set_fact:
    docker_dns_search_domains: "{{ docker_dns_search_domains + searchdomains | default([]) }}"

- name: Check system nameservers
  shell: set -o pipefail && grep "^nameserver" /etc/resolv.conf | sed -r 's/^nameserver\s*([^#\s]+)\s*(#.*)?/\1/'
  args:
    executable: /bin/bash
  changed_when: False
  register: system_nameservers
  check_mode: no

- name: Check system search domains
  # noqa risky-shell-pipe - if resolf.conf has no search domain, grep will exit 1 which would force us to add failed_when: false
  # Therefore -o pipefail is not applicable in this specific instance
  shell: grep "^search" /etc/resolv.conf | sed -r 's/^search\s*([^#]+)\s*(#.*)?/\1/'
  args:
    executable: /bin/bash
  changed_when: False
  register: system_search_domains
  check_mode: no

- name: Add system nameservers to docker options
  set_fact:
    docker_dns_servers: "{{ docker_dns_servers | union(system_nameservers.stdout_lines) | unique }}"
  when: system_nameservers.stdout

- name: Add system search domains to docker options
  set_fact:
    docker_dns_search_domains: "{{ docker_dns_search_domains | union(system_search_domains.stdout.split() | default([])) | unique }}"
  when: system_search_domains.stdout

- name: Check number of nameservers
  fail:
    msg: "Too many nameservers. You can relax this check by set docker_dns_servers_strict=false in docker.yml and we will only use the first 3."
  when: docker_dns_servers | length > 3 and docker_dns_servers_strict | bool

- name: Rtrim number of nameservers to 3
  set_fact:
    docker_dns_servers: "{{ docker_dns_servers[0:3] }}"
  when: docker_dns_servers | length > 3 and not docker_dns_servers_strict | bool

- name: Check number of search domains
  fail:
    msg: "Too many search domains"
  when: docker_dns_search_domains | length > 6

- name: Check length of search domains
  fail:
    msg: "Search domains exceeded limit of 256 characters"
  when: docker_dns_search_domains | join(' ') | length > 256
