---
- name: Set openresolv to not configure /etc/resolv.conf
  ansible.builtin.lineinfile:
    path: /etc/resolvconf.conf
    regexp: '^resolvconf='
    line: 'resolvconf=NO'


- name: Configure DNS servers
  ansible.builtin.template:
    src: resolv.conf.j2
    dest: /etc/resolv.conf
    owner: root
    group: root
    mode: '0644'


- name: Install dhcp & dns packages
  ansible.builtin.package:
    name:
      - isc-dhcp-server
      - unbound
    update_cache: no
    state: present

- name: Create custom service folders
  ansible.builtin.file:
    path: /etc/systemd/system/{{ item }}.service.d
    state: directory
    owner: root
    group: root
    mode: '0755'
  loop:
    - isc-dhcp-server
    - unbound

- name: Make services autorestart themselves on failure
  ansible.builtin.template:
    src: "custom-service-autorestart.j2"
    dest: /etc/systemd/system/{{ item }}.service.d/autorestart.conf
    owner: root
    group: root
    mode: '0644'
  loop:
    - isc-dhcp-server
    - unbound
  notify:
    - Reload systemd services
    - Restart {{ item }}

- name: Enable dhcpd and unbound services
  ansible.builtin.systemd_service:
    name: "{{ item }}"
    enabled: yes
  loop:
    - isc-dhcp-server
    - unbound


- name: Set dhcp to only run via ipv4
  ansible.builtin.lineinfile:
    path: /etc/default/isc-dhcp-server
    regexp: '^INTERFACESv4='
    line: 'INTERFACESv4="{{ dhcp_interface }}"'


- name: Copy dhcpd.conf
  ansible.builtin.template:
    src: dhcpd/dhcpd.conf.j2
    dest: /etc/dhcp/dhcpd.conf
    owner: root
    group: root
    mode: '0644'
  notify:
    - Restart isc-dhcp-server


- name: Copy unbound conf files
  ansible.builtin.template:
    src: "unbound/{{ item }}.j2"
    dest: /etc/unbound/unbound.conf.d/{{ item }}
    owner: root
    group: unbound
    mode: '0640'
  loop:
    - unbound.conf
    - local-domain.conf
    - plug-onion-addresses.conf
  notify:
    - Restart unbound

- name: Check adblock config file
  ansible.builtin.stat:
    path: /etc/unbound/unbound.conf.d/ad-servers.conf
  register: adservers_conf

- ansible.builtin.set_fact:
    adservers_conf_age_in_days: "{{ (lookup('pipe', 'date +%s')|int - adservers_conf.stat.ctime|int) / 86400 }}"
  when:
    - adservers_conf.stat.exists

- name: Download fresh adblock config
  ansible.builtin.get_url:
    url: 'https://pgl.yoyo.org/adservers/serverlist.php?hostformat=unbound&mimetype=plaintext'
    dest: /etc/unbound/unbound.conf.d/ad-servers.conf
    owner: root
    group: unbound
    mode: '0644'
  when:
    #- not adservers_conf.stat.exists or adservers_conf_age_in_days|int > 30
    - not adservers_conf.stat.exists
  notify:
    - Restart unbound

- name: Update /etc/hosts
  ansible.builtin.template:
    src: hosts.j2
    dest: /etc/hosts
    owner: root
    group: root
    mode: '0644'