---
- name: Uninstall web server packages that may conflict with nginx
  apt:
    name:
      - apache2
      - lighttpd
    state: absent

- name: Unhold nginx-related packages for updates
  dpkg_selections:
    name: "{{ nginx_pkg_select }}"
    selection: install
  loop:
    - "nginx"
    - "nginx-common"
    - "nginx-extras"
  loop_control:
    loop_var: nginx_pkg_select

- name: Remove any older nginx
  apt:
    name:
      - nginx
      - nginx-common
      - nginx-extras
    state: absent
    purge: true

- name: Install nginx
  apt:
    name:
      - nginx
      - nginx-common
      - nginx-extras

- name: Create nginx ssl directory
  file:
    path: "/etc/nginx/ssl"
    state: directory
    owner: root
    group: root
    mode: 0744

- name: Create self-signed SSL cert
  command: >-
    openssl req -new -nodes -x509 -subj "/C=US/ST=Texas/L=Austin/O=IT/CN=${ansible_fqdn}" -days 3650
    -keyout /etc/nginx/ssl/server.key -out /etc/nginx/ssl/server.crt -extensions v3_ca
  args:
    creates: /etc/nginx/ssl/server.crt

- name: Remove default nginx site symlink
  file:
    path: "/etc/nginx/sites-enabled/default"
    state: absent

- name: Add nginx global config
  template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    force: true
    backup: true
    mode: 0644

- name: Add app-specific nginx site
  template:
    src: default.j2
    dest: /etc/nginx/sites-available/00-azuracast
    force: true
    mode: 0644

- name: Link app-specific nginx site
  file:
    path: "/etc/nginx/sites-enabled/00-azuracast"
    state: link
    src: "/etc/nginx/sites-available/00-azuracast"

- name: Turn sendfile off on nginx for local development
  replace:
    dest: /etc/nginx/nginx.conf
    regexp: 'sendfile on;'
    replace: 'sendfile off;'
  when: app_env == "development"
