---
- block:
  - name: Install the core freeradius packages
    apt: pkg={{ freeradius_pkgs }} state=present cache_valid_time=3600

  - name: Install the additional freeradius packages
    apt: pkg={{ freeradius_additional_modules }} state=present cache_valid_time=3600
    notify: restart freeradius

  - name: Install the freeradius memcached module if needed
    apt: pkg=freeradius-memcached state=present cache_valid_time=3600
    when: freeradius_memcache_module
    notify: restart freeradius

  - name: Install the freeradius redis module if needed
    apt: pkg=freeradius-redis state=present cache_valid_time=3600
    when: freeradius_redis_module
    notify: restart freeradius

  tags: freeradius

- block:
  - name: Disable some modules
    file: dest=/etc/freeradius/3.0/mods-enabled/{{ item }} state=absent
    with_items: '{{ freeradius_to_be_disabled_modules }}'
    notify: restart freeradius

  - name: Enable some modules
    file: src=/etc/freeradius/3.0/mods-available/{{ item }} dest=/etc/freeradius/3.0/mods-enabled/{{ item }} state=link
    with_items: '{{ freeradius_enabled_modules }}'
    notify: restart freeradius

  tags: [ 'freeradius', 'freeradius_modules' ]

- block:
  - name: Create the freeradius pki directory if it does not yet exist
    file: dest={{ freeradius_pki_directory }} state=directory owner=root group=freerad mode=0550

  - name: Create the DH file
    command: openssl dhparam -out {{ freeradius_pki_directory }}/dh 2048
    args:
      creates: '{{ freeradius_pki_directory }}/dh'

  tags: [ 'freeradius', 'freeradius_cert' ]

- block:
  - name: Setup the freeradius private key if it is not in place already
    copy: remote_src=yes src={{ letsencrypt_acme_certs_dir }}/privkey dest={{ freeradius_pki_directory }} owner=root group=freerad mode=0440

  - name: Create the acme hooks directory if it does not yet exist
    file: dest={{ letsencrypt_acme_services_scripts_dir }} state=directory owner=root group=root

  - name: Install a script that fix the letsencrypt certificate for freeradius and then restarts the service
    template: src=freeradius-letsencrypt-acme.sh dest={{ letsencrypt_acme_services_scripts_dir }}/freeradius owner=root group=root mode=4555

  when:
    - freeradius_letsencrypt_managed
    - letsencrypt_acme_install
  tags: [ 'freeradius', 'freeradius_letsencrypt', 'letsencrypt' ]


- block:
  - name: Remove the letsencrypt certificate hook for freeradius
    file: dest=/usr/lib/acme/hooks/freeradius state=absent

  when:
    - not freeradius_letsencrypt_managed
  tags: [ 'freeradius', 'freeradius_letsencrypt', 'letsencrypt' ]

- block: 
   - name: Ensure that freeradius is started and enabled
     service: name=freeradius state=started enabled=yes

  tags: freeradius