# This role assumes that Unbound is already installed, fail early if it isn't.
- name: Check that Unbound is installed
  stat:
    path: /etc/unbound
  register: unbound_config

- name: Ensure that Unbound is installed
  assert:
    that:
      - unbound_config.stat.exists

# We only want to use ipv6 if it is both the interface ip provided by nodepool
# and a valid address on the host. We check first that the interface_ip is
# defined and ipv6 then check if there is an interface that can route ipv6.
- name: Check for IPv6
  when:
    - hostvars[inventory_hostname]['nodepool']['interface_ip'] is defined
    - hostvars[inventory_hostname]['nodepool']['interface_ip'] |ipv6
    - hostvars[inventory_hostname]['ansible_default_ipv6'] is defined
    - hostvars[inventory_hostname]['ansible_default_ipv6']['address'] is defined
  set_fact:
    unbound_use_ipv6: true

# Use *only* ipv6 resolvers if ipv6 is present and routable.  This
# avoids traversing potential NAT when using ipv4 which can be
# unreliable.
- name: Set IPv6 nameservers
  when:
    - unbound_use_ipv6 is defined
  set_fact:
    unbound_primary_nameserver: '{{ unbound_primary_nameserver_v6 }}'
    unbound_secondary_nameserver: '{{ unbound_secondary_nameserver_v6 }}'

# Fallback to default ipv4 if there is no ipv6 available as this
# causes timeouts and failovers that are unnecesary.
- name: Set IPv4 nameservers
  when:
    - unbound_use_ipv6 is not defined
  set_fact:
    unbound_primary_nameserver: '{{ unbound_primary_nameserver_v4 }}'
    unbound_secondary_nameserver: '{{ unbound_secondary_nameserver_v4 }}'

- name: Include OS-specific variables
  include_vars: "{{ item }}"
  with_first_found:
    - "{{ ansible_distribution }}.yaml"
    - "{{ ansible_os_family }}.yaml"
    - "default.yaml"

- name: Ensure Unbound conf.d directory exists
  become: true
  file:
    path: "{{ unbound_confd }}"
    state: directory
    owner: root
    group: root
    mode: "0755"

# TODO: Move this to /etc/unbound/conf.d ?
- name: Configure unbound forwarding
  become: true
  template:
    dest: /etc/unbound/forwarding.conf
    owner: root
    group: root
    mode: "0644"
    src: forwarding.conf.j2
  register: forwarding_config
  notify:
    - Restart unbound

- name: Configure unbound TTL
  become: true
  template:
    dest: "{{ unbound_confd }}/ttl.conf"
    owner: root
    group: root
    mode: "0644"
    src: ttl.conf.j2
  register: ttl_config
  notify:
    - Restart unbound

- name: Start unbound
  become: true
  service:
    name: unbound
    state: started
    enabled: true