- hosts:
    - numquam
  vars:
    container_name: odoo
    docker_tag: trygvis/odoo:12
    # Maximum allowed CPU time per request (default 60).
    limit_time_cpu: 120
    # Maximum allowed Real time per request (default 120).
    limit_time_real: 500
  tasks:
    - become: yes
      file:
        path: /etc/odoo
        state: absent

    - become: yes
      copy:
        dest: /etc/systemd/system/docker.odoo.service
        content: |
          [Unit]
          After=docker.service
          Requires=docker.service

          [Service]
          TimeoutStartSec=0
          Restart=always
          ExecStartPre=-/usr/bin/docker stop {{ container_name }}
          ExecStartPre=-/usr/bin/docker rm {{ container_name }}
          ExecStartPre=/usr/bin/docker pull {{ docker_tag }}
          ExecStart=/usr/bin/docker run \
            -e HOST=172.17.0.1 \
            -e PORT=5432 \
            -e USER=odoo \
            -e PASSWORD=odoo \
            -e ADMIN_PASSWD={{ admin_passwd }} \
            -p 8069:8069 \
            -p 8070:8070 \
            --mount source=odoo-data,target=/var/lib/odoo \
            --mount source=odoo-extra-addons,target=/mnt/extra-addons \
            -t \
            --name {{ container_name }} \
            {{ docker_tag }} \
            --workers=5 \
            --http-port=8069 \
            --longpolling-port=8070 \
            --email-from=odoo@trygvis.io \
            --smtp=172.17.0.1 \
            --proxy-mode \
            --limit-time-cpu={{ limit_time_cpu }} \
            --limit-time-real={{ limit_time_real }}

          [Install]
          WantedBy=multi-user.target
      register: service_file

    - become: yes
      systemd:
        daemon_reload: yes
      when: service_file.changed

    - become: yes
      systemd:
        unit: docker.odoo.service
        enabled: yes
        state: started
      when: not service_file.changed

    - become: yes
      systemd:
        unit: docker.odoo.service
        enabled: yes
        state: restarted
      when: service_file.changed or force_restart