---

- name: Install packages
  package: name={{ odoo_packages }}
  tags: odoo

- when: odoo_install_mode != 'none'
  block:
    - name: Fetch odoo sources
      get_url:
        url: "{{ odoo_archive_url }}"
        dest: "{{ odoo_root_dir }}/tmp"
        checksum: sha256:{{ odoo_archive_sha256 }}

    - name: Extract odoo archive
      unarchive:
        src: "{{ odoo_root_dir }}/tmp/odoo_{{ odoo_version }}.{{ odoo_build }}.tar.gz"
        dest: "{{ odoo_root_dir }}/tmp"
        remote_src: True

    - name: Copy odoo application to its final directory
      synchronize:
        src: "{{ odoo_root_dir }}/tmp/odoo-{{ odoo_version }}.post{{ odoo_build }}/"
        dest: "{{ odoo_root_dir }}/app/"
        recursive: True
        delete: True
        compress: False
      delegate_to: "{{ inventory_hostname }}"

  tags: odoo

- name: Create the virtualenv
  pip:
    state: "{{ (odoo_install_mode == 'none') | ternary('present', 'latest') }}"
    virtualenv: "{{ odoo_root_dir }}/venv"
    virtualenv_command: "{{ odoo_venv_command }}"
    requirements: "{{ odoo_root_dir }}/app/requirements.txt"
  environment:
    PATH: "{{ (pg_version == 'default') | ternary('', '/usr/pgsql-' ~ pg_version ~ '/bin:') }}/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin"
  tags: odoo

- name: Install additional modules in the venv
  pip:
    name: "{{ item }}"
    state: "{{ (odoo_install_mode == 'none') | ternary('present', 'latest') }}"
    virtualenv: "{{ odoo_root_dir }}/venv"
    virtualenv_command: "{{ odoo_venv_command }}"
  loop:
    - phonenumbers
    - python-jose
  tags: odoo

- name: Create the PostgreSQL role
  postgresql_user:
    db: postgres
    name: "{{ odoo_db_user }}"
    password: "{{ odoo_db_pass }}"
    login_host: "{{ odoo_db_server }}"
    login_user: sqladmin
    login_password: "{{ pg_admin_pass }}"
  tags: odoo

- name: Create the PostgreSQL database
  postgresql_db:
    name: "{{ odoo_db_name }}"
    encoding: UTF-8
    template: template0
    owner: "{{ odoo_db_user }}"
    login_host: "{{ odoo_db_server }}"
    login_user: sqladmin
    login_password: "{{ pg_admin_pass }}"
  tags: odoo

- name: Deploy odoo service file
  template: src=odoo-server.service.j2 dest=/etc/systemd/system/odoo-server.service
  register: odoo_unit
  notify: restart odoo-server
  tags: odoo

- name: Reload systemd
  command: systemctl daemon-reload
  when: odoo_unit.changed
  tags: odoo

- name: Install backup hooks
  template: src={{ item }}-backup.sh.j2 dest=/etc/backup/{{ item }}.d/odoo.sh mode=750
  loop:
    - pre
    - post
  tags: odoo

