---
- name: install unbound and nsd
  pkgng:
    name: "{{ item }}"
    state: present
  with_items:
    - unbound
    - nsd

# "root-hints" is the file which contains the listing of primary root
# DNS servers.  Unbound does have a listing of root DNS servers in its
# code, but we want to make sure we have the most up to date copy.
# We normally update our copy once every 6 months.
#
# References:
# * Unbound DNS Server Tutorial
#   https://calomel.org/unbound_dns.html
#
- name: unbound - fetch root.hints
  command: >
    fetch -o /usr/local/etc/unbound/root.hints
    "https://www.internic.net/domain/named.cache"
  notify: reload-unbound

- name: unbound - check existence of control key/cert
  stat:
    path: /usr/local/etc/unbound/unbound_control.key
  register: stat_result

- name: unbound - generate self-signed key/cert for control
  command: unbound-control-setup
  when: not stat_result.stat.exists

- name: unbound - copy configuration
  copy:
    src: unbound.conf
    dest: /usr/local/etc/unbound/unbound.conf
    validate: "unbound-checkconf %s"
  notify: reload-unbound

- name: unbound - enable and start service
  command: rcenable unbound

- name: setup resolv.conf
  copy:
    src: resolv.conf
    dest: /etc/resolv.conf

#
# NSD
#
- name: NSD - check existence of control key/cert
  stat:
    path: /usr/local/etc/nsd/nsd_control.key
  register: stat_result

- name: NSD - generate self-signed key/cert for control
  command: nsd-control-setup
  when: not stat_result.stat.exists

- name: NSD - create zones directory
  file:
    path: /usr/local/etc/nsd/zones
    state: directory

- name: NSD - get the list of zone files
  set_fact:
    zonefiles: "{{ lookup('fileglob', '../templates/zones/*.j2', wantlist=True) }}"
  tags: zones

- debug: var=zonefiles

- name: NSD - generate zone files
  include_tasks: nsd-zone.yml zonefile={{ item }}
  with_items: "{{ zonefiles }}"
  tags: zones

# NOTE: requires variable `zonefiles`
- name: NSD - generate configuration
  template:
    src: nsd.conf.j2
    dest: /usr/local/etc/nsd/nsd.conf
    validate: "nsd-checkconf %s"
  notify: reload-nsd
  tags: zones

- name: NSD - enable and start service
  command: rcenable nsd