# roles/dhcp/tasks/main.yml
---

- name: Load distro-specific variables
  include_vars: "{{ item }}"
  with_first_found:
    - "{{ ansible_distribution }}.yml"
    - "{{ ansible_os_family }}.yml"
    - "{{ default }}.yml"
  tags: dhcp

- name: Install packages
  become: true
  package:
    name: "{{ dhcp_packages }}"
    state: "{{ dhcp_packages_state }}"
  tags: dhcp

- name: Run AppArmor fix when appropriate
  include_tasks: apparmor-fix.yml
  when: ansible_os_family == 'Debian' and dhcp_apparmor_fix|bool
  tags: dhcp

- name: Set default listening interface on Debian and derivatives
  include_tasks: default-fix.yml
  when: ansible_os_family == 'Debian'
  tags: dhcp

- name: Install custom includes
  become: true
  template:
    src: "{{ item.0 }}"
    dest: "{{ dhcp_config_dir }}/{{ ( item.0 | basename ).split('.j2')[0] }}"
    owner: root
    group: root
    mode: "{{ item.1 | default('0644') }}"
  loop: "{{ dhcp_custom_includes | zip_longest(dhcp_custom_includes_modes | default([])) | list }}"
  when: dhcp_custom_includes is defined
  notify: Restart DHCP
  tags: dhcp

- name: Install includes
  become: true
  copy:
    src: "{{ item }}"
    dest: "{{ dhcp_config_dir }}/{{ item | basename }}"
    owner: root
    group: root
    mode: '0644'
  with_items: "{{ dhcp_global_includes }}"
  when: dhcp_global_includes is defined
  notify: Restart DHCP
  tags: dhcp

- name: Set config directory perms
  become: true
  file:
    path: "{{ dhcp_config | dirname }}"
    state: directory
    mode: '0755'
  tags: dhcp

- name: Pre check dhcpd config file - copy to tmp
  become: true
  template:
    src: etc_dhcp_dhcpd.conf.j2
    dest: /etc/dhcp/test_dhcpd.conf-test
    mode: '0644'
  #  validate: 'dhcpd -t -cf %s'
  tags: dhcp

- name: Validate file
  ansible.builtin.command:  '/usr/sbin/dhcpd -t -cf /etc/dhcp/test_dhcpd.conf-test'
  register: test_dhcpd_output
  tags: dhcp

- name: remove testfile
  become: true
  ansible.builtin.file:
    path: /etc/dhcp/test_dhcpd.conf-test
    state: absent
  tags: dhcp

- name: Debug test_dhcpd_output
  debug:
    var: test_dhcpd_output
  tags: dhcp

- name: Install config file
  become: true
  template:
    src: etc_dhcp_dhcpd.conf.j2
    dest: "{{ dhcp_config }}"
    owner: root
    mode: '0644'
    #validate: 'sudo dhcpd -t -cf %s'
  notify: Restart DHCP
  tags: dhcp
  when: not test_dhcpd_output.rc

- name: "Ensure service is {{ dhcp_global_server_state | default('started') }}"
  become: true
  service:
    name: "{{ dhcp_service }}"
    state: "{{ dhcp_global_server_state | default('started') }}"
    enabled: true
  tags: dhcp
