---
- block: 
  - name: Install the unicorn ruby-on-rails service and its dependencies
    gem: name={{ item }} state=latest
    with_items: '{{ unicorn_gems }}'

  - name: Create the unicorn pid directory
    file: dest=/var/run/unicorn state=directory owner={{ redmine_user }} group={{ redmine_user }} mode=0750
    
  - name: Install the unicorn startup file for redmine
    copy: src=redmine.init dest=/etc/init.d/redmine owner=root group=root mode=0755

  - name: Ensure that the unicorn service is enabled and running on trusty
    service: name={{ redmine_sysvinit_service_name }} state=started enabled=yes
    when: ruby_use_unicorn

  tags: [ 'ruby', 'redmine', 'unicorn' ]
  when:
    - ruby_use_unicorn
    - is_trusty

- block: 
  - name: Install the unicorn package
    apt: pkg=unicorn state=present cache_valid_time=1800

  - name: Install a nginx configuration of the unicorn backend
    template: src=nginx_unicorn.conf dest=/etc/nginx/conf.d/nginx_unicorn.conf
    notify: Restart nginx

  tags: [ 'ruby', 'redmine', 'unicorn' ]
  when:
    - ruby_use_unicorn
    - is_bionic

- block: 
  - name: Create the unicorn log directory
    file: dest={{ unicorn_log_dir }} state=directory owner={{ redmine_user }} group={{ redmine_user }} mode=0750
    
  - name: Install the unicorn defaults file
    template: src=unicorn-redmine.default.j2 dest=/etc/default/unicorn-{{ redmine_inst_name }} owner=root group=root mode=0644
    notify: Reload unicorn when needed
    
  - name: Install the unicorn logrotate file
    template: src=unicorn-logrotate.j2 dest=/etc/logrotate.d/unicorn-{{ redmine_inst_name }} owner=root group=root mode=0644

  - name: Install the unicorn config
    template: src=unicorn.conf.rb.j2 dest={{ redmine_glob_root_dir }}/{{ redmine_inst_dir }}/config/unicorn.conf.rb owner=root group=root mode=0644

  - name: Install the systemd unit that globally manages the unicorn service
    template: src=systemd_unicorn.service dest={{ redmine_glob_root_dir }}/{{ redmine_inst_dir }}/config/unicorn@.service
    register: systemd_reload

  - name: Link the systemd unit that globally manages the unicorn service
    file: src={{ redmine_glob_root_dir }}/{{ redmine_inst_dir }}/config/unicorn@.service dest=/etc/systemd/system/multi-user.target.wants/unicorn@.service state=link

  - name: Reload systemd after the system unit installation
    systemd: daemon_reload=yes
    when: systemd_reload is changed

  - name: Ensure that the unicorn service for redmine is started and enabled
    service: name={{ redmine_systemd_service_name }} state=started enabled=yes
    ignore_errors: True

  tags: [ 'ruby', 'redmine', 'unicorn' ]
  when: ruby_use_unicorn