---
- hosts: asterisk
  remote_user: deploy
  become: yes
  vars:
    - redis_bind_interface: 0.0.0.0
  roles:
    - ansible-role-redis

  tasks:
  - name: install packages
    apt: name={{ item }} update_cache=yes state=latest cache_valid_time=86400
    with_items:
        - asterisk
        - asterisk-modules
        - asterisk-config
        - asterisk-core-sounds-en
        - asterisk-core-sounds-en-gsm
        - asterisk-moh-opsound-gsm
        - composer
        - php-cli
        - php-common
        - php-json
        - php-mbstring
        - php-bcmath
        - php-intl
        - php-dev
        - php-pear
        - php-redis

  - name: create project folder
    file:
      path: /opt/callcenter
      state: directory
      mode: 0755

  - name: create project log folder
    file:
      path: /opt/callcenter/log
      state: directory
      mode: 0777
      recurse: true

  - name: copy PHP source
    copy:
      src: "{{ item }}"
      dest: /opt/callcenter
    with_items:
      - ../server.php
      - ../src
      - ../composer.json
      - ../composer.lock

  - name: copy environment file
    copy:
      src: .env
      dest: /opt/callcenter

  - name: copy static source
    copy:
      src: "{{ item }}"
      dest: /usr/share/asterisk/static-http
    with_items:
      - ../public/static/

  - name: install PHP dependencies with Composer
    command: composer install --no-dev --prefer-dist
    args:
      chdir: /opt/callcenter

  - name: copy asterisk etc folder to project
    synchronize:
      src: asterisk/etc/
      dest: /etc/asterisk/
    notify:
      - reload asterisk

  - name: Kill PHP processes
    command: killall php
    ignore_errors: yes

  - debug: msg="Restart PHP processes"
    changed_when: True
    notify:
      - start server

  handlers:
    - name: reload asterisk
      shell: asterisk -rx'core reload'

    - name: start server
      shell: cd /opt/callcenter; nohup php /opt/callcenter/server.php </dev/null >/dev/null 2>&1 &
