# 2020-01-22: Package 'uwsgi' is installed by nginx/tasks/install.yml for
# Captive Portal (responds to browsers trying to detect a Captive Portal) and
# also for Admin Console.

# IIAB makes the 'uwsgi' service mandatory for now (see Line 45) but this could
# perhaps be auto-disabled in future (or never installed?)  e.g. if Captive
# Portal + Admin Console are both unneeded...and impact of uWSGI is too high ?

- name: Stop 'uwsgi' systemd service (may include 3 child processes for Captive Portal, and 3 child processes for Admin Console)
  systemd:
    name: uwsgi
    state: stopped

- name: Install /etc/uwsgi/apps-enabled/captiveportal.ini from template (if captiveportal_enabled)
  template:
    src: captiveportal.ini.j2
    dest: /etc/uwsgi/apps-enabled/captiveportal.ini
  when: captiveportal_enabled

- name: Delete /etc/uwsgi/apps-enabled/captiveportal.ini (if not captiveportal_enabled)
  file:
    path: /etc/uwsgi/apps-enabled/captiveportal.ini
    state: absent
  when: not captiveportal_enabled

- name: Symlink /etc/nginx/sites-enabled/capture.conf -> /etc/nginx/sites-available/capture.conf to enable NGINX to service the sites in checkurls list (if captiveportal_enabled)
  file:
    src: /etc/nginx/sites-available/capture.conf
    path: /etc/nginx/sites-enabled/capture.conf
    state: link
  when: captiveportal_enabled

- name: Delete symlink /etc/nginx/sites-enabled/capture.conf to disable NGINX to location definitions for checkurls (if not captiveportal_enabled)
  file:
    path: /etc/nginx/sites-enabled/capture.conf
    state: absent
  when: not captiveportal_enabled

- name: Run /usr/sbin/iiab-divert-to-nginx to generate diversion lists for NGINX
  command: /usr/sbin/iiab-divert-to-nginx
  when: captiveportal_enabled

- name: Delete /etc/dnsmasq.d/capture to make sure dnsmasq is not diverting (if not captiveportal_enabled)
  file:
    path: /etc/dnsmasq.d/capture
    state: absent
  when: not captiveportal_enabled

# Let's assume (for now) that Admin Console was/will be installed. Disabling of
# uWSGI's service can be implemented later as nec, e.g. if CP+AC both disabled?
- name: Start & Enable 'uwsgi' systemd service (may include 3 child processes for Captive Portal, and 3 child processes for Admin Console)
  systemd:
    name: uwsgi
    daemon_reload: yes
    state: started
    enabled: true

# Unify 2 stanzas below ('state: restarted') when we end Ubuntu 16.04 support.
- name: Stop 'dnsmasq' systemd service (if dnsmasq_enabled)
  systemd:
    name: dnsmasq
    state: stopped
  when: dnsmasq_enabled

- name: Start 'dnsmasq' systemd service (if dnsmasq_enabled)
  systemd:
    name: dnsmasq
    state: started
  when: dnsmasq_enabled