---
# Requirement: Install firewalld after installing libvirt
- name: Install firewalld packages
  ansible.builtin.apt:
    name:
      - firewalld
  register: result

- name: Stop firewalld-service
  ansible.builtin.systemd:
    name: firewalld
    state: stopped
  when: result.changed # noqa: no-handler

- name: Disable firewalld-service
  ansible.builtin.systemd:
    name: firewalld
    enabled: false

- name: Add virbr0 to libvirt zone
  ansible.posix.firewalld:
    zone: libvirt
    interface: virbr0
    permanent: true
    state: enabled
  when: vm_support is defined and vm_support

- name: Permit access to cups from libvirt
  ansible.posix.firewalld:
    zone: libvirt
    port: 631/tcp
    permanent: true
    state: enabled
  when: vm_support is defined and vm_support # and printing is defined and printing

- name: Permit access to usersquid from libvirt
  ansible.posix.firewalld:
    zone: libvirt
    port: 3128/tcp
    permanent: true
    state: enabled
  when: vm_support is defined and vm_support # and localsquid is defined and localsquid

- name: Copy some scripts
  ansible.builtin.copy:
    src: "{{ item }}"
    dest: /usr/local/sbin/
    mode: '0755'
  loop:
    - pam-exec.sh
    - rmexam

- name: Append teacherPC to exam_destination_allowed_ipv4 addresses
  ansible.builtin.set_fact:
    exam_destination_allowed_ipv4: "{{ exam_destination_allowed_ipv4 + (exam_teacherpc_ips | default([ ansible_default_ipv4.address.rsplit('.', 1)[0] ~ '.' ~ exam_teacherpc_last_digit ])) }}"
  when:
    - exam_destination_allowed_ipv4 is defined
    - exam_destination_allowed_ipv4 | length > 0
    - exam_teacherpc_ips is defined or exam_teacherpc_last_digit | default('') | string | length > 0

- name: Install no-way-out-policy
  ansible.builtin.template:
    src: no-way-out.xml.j2
    dest: "/etc/firewalld/policies/no-way-out-{{ item }}.xml"
    mode: '0644'
  vars:
    zones:
      - HOST
      - "{{ 'libvirt' if vm_support | default(false) else '' }}"
  loop: "{{ zones | reject('match','^$') }}"
  when:
    - exam_destination_allowed_ipv4 is defined
    - exam_destination_allowed_ipv4 | length > 0

- name: Install no-way-out nf-table for macvtap device
  ansible.builtin.template:
    src: no-way-out-nftable.j2
    dest: "/usr/local/sbin/no-way-out-nftable"
    mode: '0755'
  when:
    - exam_destination_allowed_ipv4 is defined
    - exam_destination_allowed_ipv4 | length > 0
    - vm_support is defined and vm_support

- name: Enable login script via pam_exec.so
  ansible.builtin.lineinfile:
    dest: /etc/pam.d/common-session
    line: 'session optional        pam_exec.so /usr/local/sbin/pam-exec.sh'

- name: Provide rmexam services and timers for some scripts
  ansible.builtin.copy:
    src: "{{ item }}"
    dest: "/etc/systemd/system/{{ item }}"
    mode: '0644'
  loop:
    - rmexam.service
    - rmexam.timer

- name: Enable rmexam.timer
  ansible.builtin.systemd:
    name: rmexam.timer
    enabled: true
