# SPDX-License-Identifier: BSD-3-Clause
---
- name: Debug
  debug:
    msg: facts {{ ansible_facts | to_nice_json }}

# This task can be removed once the RHEL-8.5 is not tested anymore
- name: Install hostapd via CentOS Stream
  command: dnf -y install http://mirror.centos.org/centos/8-stream/AppStream/x86_64/os/Packages/hostapd-2.10-1.el8.x86_64.rpm  # noqa yaml[line-length]
  when:
    - ansible_distribution_version is version('8.6', '<')
    - ansible_distribution_major_version == '8'
    - ansible_distribution == 'RedHat'
  changed_when: false

- name: Install hostapd
  package:
    name: hostapd
    state: present
    use: "{{ (__network_is_ostree | d(false)) |
      ternary('ansible.posix.rhel_rpm_ostree', omit) }}"
  register: __install_status
  until: __install_status is success
  retries: 6
  delay: 10

- name: Create directory for test certificates
  file:
    state: directory
    path: /etc/pki/tls/hostapd_test
    mode: "0755"
- name: Copy server certificates
  copy:
    src: "{{ item }}"
    dest: "/etc/pki/tls/hostapd_test/{{ item }}"
    mode: "0644"
  with_items:
    - server.key
    - dh.pem
    - server.pem
    - cacert.pem

- name: Create test interfaces
  shell: |
    ip link add veth1 type veth peer name veth1-br
    ip link add veth2 type veth peer name veth2-br

    ip link add br1 type bridge
    ip link set br1 up

    ip netns add ns1

    ip link set veth1 netns ns1

    ip netns exec ns1 ip addr add 203.0.113.1/24 dev veth1

    ip link set veth1-br up
    ip link set veth2-br up

    ip link set veth1-br master br1
    ip link set veth2-br master br1

    ip netns exec ns1 ip link set veth1 up
    ip link set veth2 up

    # Enable forwarding of EAP 802.1x messages through software bridge "br1".
    echo 8 > /sys/class/net/br1/bridge/group_fwd_mask
  changed_when: false

- name: Create hostapd config
  copy:
    content: |
      interface=veth1
      driver=wired
      debug=2
      ieee8021x=1
      eap_reauth_period=3600
      eap_server=1
      use_pae_group_addr=1
      eap_user_file=/etc/hostapd/hostapd.eap_user
      ca_cert=/etc/pki/tls/hostapd_test/cacert.pem
      dh_file=/etc/pki/tls/hostapd_test/dh.pem
      server_cert=/etc/pki/tls/hostapd_test/server.pem
      private_key=/etc/pki/tls/hostapd_test/server.key
      private_key_passwd=test
      logger_syslog=-1
      logger_syslog_level=0
    dest: /etc/hostapd/wired.conf
    mode: "0644"

- name: Create eap_user_file config
  copy:
    content: |
      * TLS
    dest: /etc/hostapd/hostapd.eap_user
    mode: "0644"

- name: Run hostapd in namespace
  shell: ip netns exec ns1 hostapd -B /etc/hostapd/wired.conf && sleep 5
  changed_when: false
