---

- name: install soju
  become: yes
  apt: name="soju"
  notify: restart soju

- name: install soju db schema file
  become: yes
  template:
    src: "setup_db.psql.j2"
    dest: "/tmp/setup_db_soju.psql"
    owner: "postgres"
    group: "postgres"
    mode: "0600"

- name: setup soju db
  become: yes
  become_user: "postgres"
  command: "psql -f /tmp/setup_db_soju.psql"
  changed_when: false

- name: create soju data dir
  become: yes
  file:
    path: "{{soju_data_dir}}"
    state: "directory"
    owner: "{{soju_user}}"
    group: "{{soju_user}}"
    mode: "0755"

- name: configure soju
  become: yes
  template:
    src: "config.j2"
    dest: "/etc/soju/config"
    mode: "0644"
  notify: restart soju

- name: enable soju service
  become: yes
  systemd: name="soju.service" enabled="yes" state="started"

- name: flush handlers to ensure soju is restarted with latest config
  meta: flush_handlers

- name: create soju admin user
  become: yes
  become_user: "{{soju_user}}"
  shell: "echo '{{soju_admin_password}}' | sojudb -config /etc/soju/config create-user {{soju_admin_user}} -admin"
  register: soju_create_user
  changed_when: soju_create_user.rc == 0
  failed_when: soju_create_user.rc != 0 and 'duplicate key' not in soju_create_user.stderr
  no_log: true

- name: install nginx stream config
  become: yes
  template:
    src: "nginx-stream.conf.j2"
    dest: "/etc/nginx/streams-available/soju.conf"
  notify: reload nginx

- name: enable nginx stream config
  become: yes
  file:
    src: "/etc/nginx/streams-available/soju.conf"
    dest: "/etc/nginx/streams-enabled/soju.conf"
    state: "link"
  notify: reload nginx
