---
- name: Install knotd and dnspython
  apt:
    name:
      - knot
      - python3-dnspython

- name: Install config files
  template:
    src: knot.conf.j2
    dest: /etc/knot/knot.conf
    owner: root
    group: knot
    mode: u=rw,g=r,o=
  notify:
    - Restart knotd

- name: Create zones directory
  file:
    path: "{{ knotd__zones_dir }}"
    state: directory
    owner: root 
    group: "{{ knotd__group }}"
    mode: u=rwx,g=rx,o=

- name: Create zone files
  dns_zone:
    path: "{{ knotd__zones_dir }}/{{ item.key }}.zone"
    owner: root
    group: "{{ knotd__group }}"
    mode: u=rw,g=r,o=
    origin: "{{ item.key }}"
    soa:
      mname: "{{ item.value.soa.mname }}"
      rname: "{{ item.value.soa.rname | default(knotd__soa_rname)
                                                | default(omit) }}"
      refresh: "{{ item.value.soa.refresh | default(knotd__soa_refresh)
                   | community.general.to_seconds | int }}"
      retry: "{{ item.value.soa.retry | default(knotd__soa_retry)
                 | community.general.to_seconds | int }}"
      expire: "{{ item.value.soa.expire | default(knotd__soa_expire)
                  | community.general.to_seconds | int }}"
      minimum: "{{ item.value.soa.minimum | default(knotd__soa_minimum)
                   | community.general.to_seconds | int }}"
    hosts: "{{ item.value.hosts | default(omit) }}"
    reverse_hosts: "{{ item.value.reverse_hosts | default(omit) }}"
    ns: "{{ item.value.ns | default(omit) }}"
    mx: "{{ item.value.mx | default(omit) }}"
    cname: "{{ item.value.cname | default(omit) }}"
    txt: "{{ item.value.txt | default(omit) }}"
    a: "{{ item.value.a | default(omit) }}"
    spf: "{{ item.value.spf | default(omit) }}"
    srv: "{{ item.value.srv | default(omit) }}"
    ptr: "{{ item.value.ptr | default(omit) }}"
    aaaa: "{{ item.value.aaaa | default(omit) }}"
  when: "item.value.master is not defined
         and (item.value.enabled | default(true))"
  loop: "{{ knotd__zones | dict2items }}"
  notify:
    - Reload knotd

- name: Remove disabled zone files
  file:
    path: "{{ knotd__zones_dir }}/{{ item.key }}.zone"
    state: absent
  when: "item.value.master is not defined
         and not (item.value.enabled | default(true))"
  loop: "{{ knotd__zones | dict2items }}"

- name: Enable and start knotd
  systemd:
    name: knot.service
    enabled: true
    state: started
...