---
# - hosts: all
#   tasks:
#     - name: Print some debug information
#       vars:
#         msg: |
#             Module Variables ("vars"):
#             --------------------------------
#             {{ vars | to_nice_json }}

#             Environment Variables ("environment"):
#             --------------------------------
#             {{ environment | to_nice_json }}

#             GROUP NAMES Variables ("group_names"):
#             --------------------------------
#             {{ group_names | to_nice_json }}

#             GROUPS Variables ("groups"):
#             --------------------------------
#             {{ groups | to_nice_json }}

#             HOST Variables ("hostvars"):
#             --------------------------------
#             {{ hostvars | to_nice_json }}

#       debug:
#         msg: "{{ msg.split('\n') }}"
#       tags: debug_info
#
# Localhost actions
#
- hosts: localhost
  connection: local
  vars:
    irinotes_build_dir: "{{playbook_dir}}/build/tmp/irinotes/"
    backend_build_dir: "{{playbook_dir}}/build/tmp/irinotes/src"
    client_dir: "{{playbook_dir}}/build/tmp/irinotes/client"
  tasks:

    - name: mkdir build folder
      file:
        path: "{{playbook_dir}}/build/tmp"
        state: directory

    - name: clear irinotes checkout dir if exists
      file:
        path: "{{irinotes_build_dir}}"
        state: absent

    - name: checkout irinotes
      hg:
        repo: "{{irinotes_repo}}"
        version: "{{irinotes_version}}"
        force: yes
        dest: "{{irinotes_build_dir}}"

    - name: make irinotes py package
      command: python setup.py sdist chdir="{{backend_build_dir}}"

#
# all actions
#
- hosts: remote_backend
  vars:
    backend_build_dir: "{{playbook_dir}}/build/tmp/irinotes/src"
    client_dir: "{{playbook_dir}}/build/tmp/irinotes/client"
  tasks:

    - name: get backend version
      local_action: command python setup.py -V chdir="{{backend_build_dir}}"
      register: backend_version

    - name: get discussion package version
      set_fact:
        backend_pkg_version: "{{backend_version.stdout}}"

#
# Localhost actions
#
- hosts: localhost
  connection: local
  vars:
    backend_build_dir: "{{playbook_dir}}/build/tmp/irinotes/src"
    client_dir: "{{playbook_dir}}/build/tmp/irinotes/client"
  tasks:

# build client js
    - name: remove build
      file: path="{{client_dir}}/build" state=absent

    - name: client yarn install
      command: npm install --no-save yarn
      args:
        chdir: "{{client_dir}}"

    - name: client dependencies install
      command: npx yarn install
      args:
        chdir: "{{client_dir}}"

    - name: client build
      command: npx yarn build
      args:
        chdir: "{{client_dir}}"
      environment:
        REACT_APP_API_ROOT_URL: "{{api_root_url}}"
        REACT_APP_BASENAME: "{{api_root_url}}"
        REACT_APP_NETWORK_STATUS_INTERVAL: "{{network_status_interval}}"
        REACT_APP_NETWORK_STATUS_TIMEOUT: "{{network_status_timeout}}"
        REACT_APP_SYNC_INTERVAL: "{{sync_interval}}"

#
# Static server
#
- hosts: remote_static
  become: yes
  vars:
    backend_build_dir: "{{playbook_dir}}/build/tmp/irinotes/src"
    client_dir: "{{playbook_dir}}/build/tmp/irinotes/client"
  tasks:

    - name: create dest static directory content
      file:
        path: "{{remote_static_path}}"
        state: directory
        owner: "{{static_http_user}}"
        group: "{{static_http_group}}"

    - name: remove dest static directory content
      command: /bin/rm -fr "{{remote_static_path}}/*" warn=False
      when: remote_static_path != ""

    - name: transfert static dist to remote
      copy:
        src: "{{client_dir}}/build/"
        dest: "{{remote_static_path}}/"
        owner: "{{static_http_user}}"
        group: "{{static_http_group}}"
      notify:
        - restart static nginx

    - name: create refresh nginx config
      template:
        src: "{{static_nginx_use_ssl | ternary('nginx.static.ssl.conf.j2', 'nginx.static.conf.j2')}}"
        dest: "{{static_nginx_config | default('/etc/nginx/site-available/'+static_server_name, true)}}"
      notify:
        - restart static nginx

  handlers:
    - name: restart static nginx
      service:
        name: "{{static_http_service}}"
        state: restarted
      ignore_errors: yes

#
# backend servers
#
- hosts: remote_backend
  become: yes
  vars:
    backend_build_dir: "{{playbook_dir}}/build/tmp/irinotes/src"
  tasks:

    - name: add iri group
      group:
        name: iri

    - name: add uwsgi user
      user:
        name: uwsgi
        group: iri
        home: /var/www
        create_home: no
        system: yes
        shell: /bin/false

    - name: create log dir
      file:
        path: "{{log_base_path}}"
        state: directory
        owner: uwsgi
        group: iri
        mode: 0755

    - name: create config dir
      file:
        path: "{{backend_config_base}}"
        state: directory
        owner: uwsgi
        group: iri
        mode: 0755

    - name: create config dir requirements
      file:
        path: "{{backend_config_base}}/requirements"
        state: directory
        owner: uwsgi
        group: iri
        mode: 0755

    - name: create static folder
      file:
        path: "{{backend_static_root}}"
        state: directory
        owner: uwsgi
        group: iri
        mode: 0755

    - name: create media folder
      file:
        path: "{{backend_media_root}}"
        state: directory
        owner: uwsgi
        group: iri
        mode: 0755

    - name: install backend venv
      block:
        - name: register backend virtualenv stats
          stat: path="{{backend_venv}}"
          register: backend_venv_stats

        - name: copy backend base requirement file
          copy:
              src: "{{backend_build_dir}}/requirements/base.txt"
              dest: "{{backend_config_base}}/requirements/base.txt"
          register: copy_backend_requirements_base

        - name: copy backend prod requirement file
          copy:
              src: "{{backend_build_dir}}/requirements/prod.txt"
              dest: "{{backend_config_base}}/requirements/prod.txt"
          register: copy_backend_requirements_prod


        - name: remove annotation api venv
          file:
              path: "{{backend_venv}}"
              state: absent
          when: copy_backend_requirements_base.changed or copy_backend_requirements_prod.changed

        - name: create backend virtualenv
          pip:
              virtualenv_command: /usr/bin/python3 -m venv
              virtualenv: "{{backend_venv}}"
              name: pip
              state: latest
          when: (copy_backend_requirements_base.changed or copy_backend_requirements_prod.changed) or (not backend_venv_stats.stat.exists)

        - name: virtualenv install requirements
          pip:
              virtualenv: "{{backend_venv}}"
              requirements: "{{backend_config_base}}/requirements/prod.txt"
          when: (copy_backend_requirements_base.changed or copy_backend_requirements_prod.changed) or (not backend_venv_stats.stat.exists)
          notify: restart irinotes backend service

        - name: copy backend config
          template:
            src: "backend_settings.ini.j2"
            dest: "{{backend_config_base}}/settings.ini"
          notify: restart irinotes backend service

        # install irinotes
        - name: create temporary install directory
          tempfile:
              state: directory
              suffix: build
          register: backend_temp_folder

        - name: copy irinotes backend build
          copy:
              src: "{{backend_build_dir}}/dist/irinotes-{{backend_pkg_version}}.tar.gz"
              dest: "{{backend_temp_folder.path}}/irinotes-{{backend_pkg_version}}.tar.gz"

        - name: virtualenv remove irinotes
          pip:
              virtualenv: "{{backend_venv}}"
              name: irinotes
              state: absent
          notify: restart irinotes backend service

        - name: virtualenv install irinotes
          pip:
              virtualenv: "{{backend_venv}}"
              name: "file://{{backend_temp_folder.path}}/irinotes-{{backend_pkg_version}}.tar.gz"
          notify: restart irinotes backend service

        - name: irinotes migrate
          command: "{{backend_venv}}/bin/django-admin migrate --noinput"
          args:
            chdir: "{{backend_venv}}"
          environment:
            DJANGO_SETTINGS_MODULE: "irinotes.settings"
            IRINOTES_CONFIG_BASE: "{{backend_config_base}}"
          become: yes
          become_user: uwsgi
          notify: restart irinotes backend service

        - name: irinotes collectstatic
          command: "{{backend_venv}}/bin/django-admin collectstatic --noinput -c"
          args:
            chdir: "{{backend_venv}}"
          environment:
            DJANGO_SETTINGS_MODULE: "irinotes.settings"
            IRINOTES_CONFIG_BASE: "{{backend_config_base}}"
          become: yes
          become_user: uwsgi
          notify: restart irinotes backend service

      always:
        - name: remove temp folder
          file:
            state: absent
            path: "{{backend_temp_folder.path}}"
          when: backend_temp_folder is defined


    - name: copy backend uwsgi config
      template:
        src: "uwsgi_irinotes.yml.j2"
        dest: "{{backend_config_base}}/uwsgi_irinotes.yml"
      notify: restart irinotes backend service

    - name: copy annotations api supervisor config
      template:
        src: "supervisord_irinotes_backend.ini.j2"
        dest: "{{backend_supervisor_conf_path}}/irinotes_backend.ini"
      notify: restart irinotes backend service

    - name: Add uwsgi app (reread + add)
      supervisorctl: name=irinotes_backend state=present

  handlers:
    - name: reload backend service supervisorctl
      listen: "restart irinotes backend service"
      supervisorctl:
        name: irinotes_backend
        state: restarted
      ignore_errors: yes
