---
- name: Set facts depending on OS family (Debian)
  ansible.builtin.set_fact:
    etc_freeradius: /etc/freeradius
    lib_freeradius: /usr/lib/freeradius
    log_freeradius: /var/log/freeradius
    run_freeradius: /var/run/freeradius
    fr_service_name: freeradius
    fr_service_owner: freerad
    fr_service_group: freerad
  when:
    ansible_facts['os_family'] == "Debian"

- name: Set facts depending on OS family (CentOS/RHEL)
  ansible.builtin.set_fact:
    etc_freeradius: /etc/raddb
    lib_freeradius: /usr/lib64/freeradius
    log_freeradius: /var/log/radius
    run_freeradius: /var/run/radiusd
    fr_service_name: radiusd
    fr_service_owner: radiusd
    fr_service_group: radiusd
  when:
    ansible_facts['os_family'] == "RedHat"

- name: Get current version
  ansible.builtin.shell: "set -o pipefail && radiusd -v | cut -f3 -d' ' | head -n2 | tail -n1"
  register: current_version
  args:
    executable: /bin/bash
  changed_when: false
  failed_when: false

- name: Check if radiusd is already installed
  ansible.builtin.debug:
    msg: "Current radiusd version is {{ current_version.stdout }}"

# - name: Compile radius from source code
#  ansible.builtin.include_tasks: build.yml
#  when: current_version.stdout != freeradius_version and build is true

- name: Install radius from packages
  ansible.builtin.include_tasks: install.yml

- name: Installing clients.conf
  ansible.builtin.template:
    src: clients.conf.j2
    dest: '{{ etc_freeradius }}/clients.conf'
    mode: '0644'

- name: Install radius users
  ansible.builtin.include_tasks: local-auth.yml
  when: radius_users is defined

# - name: Backup eap mod
#  ansible.builtin.copy:
#    src: '{{ etc_freeradius }}/mods-available/eap'
#    dest: '{{ etc_freeradius }}/mods-available/eap.bkp'
#    mode: '0644'
#    remote_src: true
#    backup: true

# - name: Installing eap.conf
#  ansible.builtin.copy:
#    src: eap.conf
#    dest: '{{ etc_freeradius }}/mods-available/eap'
#    mode: '0644'

- name: Enable eap mod
  ansible.builtin.file:
    src: '{{ etc_freeradius }}/mods-available/eap'
    dest: '{{ etc_freeradius }}/mods-enabled/eap'
    state: link

# - name: Backup sql mod
#  ansible.builtin.copy:
#    src: '{{ etc_freeradius }}/mods-available/sql'
#    dest: '{{ etc_freeradius }}/mods-available/sql.bkp'
#    mode: '0644'
#    remote_src: true
#    backup: true

- name: Installing mysql.conf
  ansible.builtin.template:
    src: mysql.conf.j2
    dest: '{{ etc_freeradius }}/mods-available/sql'
    mode: '0644'
  when: radius_db_name is defined

- name: Enable sql mod
  ansible.builtin.file:
    src: '{{ etc_freeradius }}/mods-available/sql'
    dest: '{{ etc_freeradius }}/mods-enabled/sql'
    state: link
  when: radius_db_name is defined

# - ansible.buildin.include_tasks: mysql.yml

- name: Restart radiusd
  ansible.builtin.systemd:
    name: "{{ fr_service_name }}.service"
    daemon_reload: true
    state: restarted
    enabled: true
