- name: Create temporary commento directories
  file: state=directory path={{ item }}
  with_items:
    - /root/commento
    - /root/commento/commento-{{ commento_version }}

- name: Download commento {{ commento_version }} release
  get_url:
    url="{{ commento_release }}"
    dest=/root/commento/commento-{{ commento_version }}.tar.gz

- name: Decompress commento release
  unarchive: src=/root/commento/commento-{{ commento_version }}.tar.gz
             dest=/root/commento/commento-{{ commento_version }} copy=no
             creates=/root/commento/commento-{{ commento_version }}/commento

- name: Create commento working directory
  file: state=directory path=/home/{{ main_user_name }}/commento

- name: Stop old commento instance
  service: name=commento state=stopped
  ignore_errors: True

- name: Copy commento data to working directory
  shell: cp -r commento/commento-{{ commento_version }}/* /home/{{ main_user_name }}/commento/ chdir=/root

- name: Setup permissions for commento
  file: path=/home/{{ main_user_name }}/commento owner={{ main_user_name }} group=www-data recurse=yes

- name: Add commento postgres user
  postgresql_user:
    login_host=localhost
    login_user={{ db_admin_username }}
    login_password="{{ db_admin_password }}"
    name={{ commento_db_username }}
    password="{{ commento_db_password }}"
    encrypted=yes
    state=present

- name: Create commento database
  postgresql_db:
    login_host=localhost
    login_user={{ db_admin_username }}
    login_password="{{ db_admin_password }}"
    name={{ commento_db_database }}
    state=present
    owner={{ commento_db_username }}

- name: Add systemd service to start commento automatically
  template:
    src=etc_systemd_system_commento.j2
    dest=/etc/systemd/system/commento.service
    owner=root
    group=root

- name: Register new commento service
  systemd: name=commento daemon_reload=yes enabled=yes

- name: Start new commento instance
  service: name=commento state=started

- name: Create the Apache Commento sites config files
  template:
    src=etc_apache2_sites-available_commento.j2
    dest=/etc/apache2/sites-available/commento_{{ item.name }}.conf
    owner=root
    group=root
  notify: restart apache
  with_items: "{{ virtual_domains }}"

- name: Enable Apache sites (creates new sites-enabled symlinks)
  command: a2ensite commento_{{ item }}.conf creates=/etc/apache2/sites-enabled/commento_{{ item }}.conf
  notify: restart apache
  with_items: "{{ virtual_domains | json_query('[*].name') }}"