---

- name: Enable matrix apt-key
  apt_key: url="https://packages.matrix.org/debian/matrix-org-archive-keyring.gpg"

- name: Enable matrix repository
  apt_repository: repo="deb https://packages.matrix.org/debian/ {{ ansible_distribution_release }} main"

- name: Install matrix
  apt:
    name:
    - matrix-synapse-py3
    - postgresql
    - python3-psycopg2

- name: Configure PostgreSQL database
  postgresql_db: name={{ matrix_dbname }} lc_collate=C lc_ctype=C template=template0
  become: true
  become_user: postgres

- name: Configure PostgreSQL user
  postgresql_user: db={{ matrix_dbname }} name={{ matrix_dbuser }} password={{ matrix_dbpass }} priv=ALL state=present
  become: true
  become_user: postgres

- name: Configure matrix
  template: src=matrix-synapse/{{ item }}.j2 dest=/etc/matrix-synapse/{{ item }}
  with_items:
  - homeserver.yaml
  - log.yaml
  - conf.d/server_name.yaml
  notify: Restart matrix-synapse

- name: Ensure certificates are available
  command: openssl req -x509 -nodes -newkey rsa:2048 -keyout /etc/nginx/ssl/{{ matrix_domain }}.key -out /etc/nginx/ssl/{{ matrix_domain }}.crt -days 730 -subj "/CN={{ matrix_domain }}" creates=/etc/nginx/ssl/{{ matrix_domain }}.crt
  notify: Restart nginx

- name: Configure certificate manager for matrix
  template: src=certs.j2 dest=/etc/acertmgr/{{ matrix_domain }}.conf
  notify: Run acertmgr

- name: Configure vhost
  template: src=vhost.j2 dest=/etc/nginx/sites-available/matrix
  notify: Restart nginx

- name: Enable vhost
  file: src=/etc/nginx/sites-available/matrix dest=/etc/nginx/sites-enabled/matrix state=link
  notify: Restart nginx