- tags:
    - bind
    - bind_packages
  become: yes
  vars:
    items:
      - bind9
      - bind9utils
      - dnsutils
  apt:
    install_recommends: no
    name: "{{ items }}"

- tags:
    - bind
    - bind_ufw
  when: bind__ufw
  become: yes
  ufw:
    name: Bind9
    rule: allow

- tags:
    - bind
    - update-passwords
  become: yes
  copy:
    dest: /etc/bind/rndc.key
    content: |
      key "rndc-key" {
          algorithm hmac-md5;
          secret "{{ bind__rndc_key }}";
      };

- tags:
    - bind
    - bind_files
  local_action:
    module: find
    paths: "./files/{{ ansible_hostname }}/bind"
    recurse: yes
  register: all_files

- tags:
    - bind
    - bind_files
  become: yes
  vars:
    files: "{{ all_files.files|map(attribute='path') | map('regex_replace', '^files/' + ansible_hostname + '/bind/', '') | flatten | sort }}"
    conf_files: "{{ files | map('regex_findall', '^named\\.conf\\..*') | flatten }}"
    dirs: "{{ files | map('regex_replace', '[^/]*$', '') | flatten | unique }}"
  block:
    # - debug: var=all_files
    - debug: var=files
    - debug: var=dirs
    - debug: var=conf_files
    - with_items: "{{ dirs }}"
      file:
        path: "/etc/bind/{{ item }}"
        state: directory

    - with_items: "{{ files }}"
      copy:
        dest: "/etc/bind/{{ item }}"
        src: "{{ ansible_hostname + '/bind/' + item }}"

#    - name: Generate named.conf.ansible
#      copy:
#        dest: /etc/bind/named.conf.ansible
#        content: |
#          {% for f in zone_files.files %}
#          zone "/etc/bind/{{ '/'.join(f.path.split('/')[3:]) }}";
#          {% endfor %}

    - name: Register named.conf.ansible
      with_items: "{{ conf_files }}"
      lineinfile:
        path: /etc/bind/named.conf.local
        line: "include \"/etc/bind/{{ item }}\";"
        regexp: "{{ item }}"