#################################################
# DO Community Playbooks: Docker
#################################################
---
- hosts: all
  become: true
  vars_files:
    - vars/default.yml

  tasks:
    - name: Pull Nextcloud image
      docker_image:
        name: "{{ container_image }}"
        source: pull
        force_source: yes

    - name: Copy dockerfile
      synchronize: src=web dest=/tmp

    - name: Build nginx webserver image
      docker_image:
        name: nextcloud-web
        build:
          path: /tmp/web/
          dockerfile: /tmp/web/Dockerfile
          pull: yes
        state: present
        source: build
        force_source: yes

    - name: Create Nextcloud container
      docker_container:
        name: "{{ container_name }}"
        image: "{{ container_image }}"
        state: started
        restart_policy: "unless-stopped"
        env:
          POSTGRES_DB: "{{ db_name }}"
          POSTGRES_USER: "{{ db_user }}"
          POSTGRES_PASSWORD: "{{ db_pass }}"
          POSTGRES_HOST: "{{ db_host }}"
#          REDIS_HOST: "redis"
        links:
          - "postgres:db"
#          - "redis:redis"
        published_ports:
          - "127.0.0.1:9000:9000"
        volumes:
          - /var/lib/nextcloud:/var/www/html

    - name: Create webserver container
      docker_container:
        name: cloud-web
        image: nextcloud-web
        state: started
        restart_policy: "unless-stopped"
        links:
          - "cloud:app"
        published_ports:
          - "127.0.0.1:9080:80"
        volumes:
          - /var/lib/nextcloud:/var/www/html:ro

    - name: Add cron job
      cron:
        name: Nextcloud cron
        minute: "*/5"
        job: "docker exec -u www-data {{ container_name }} php cron.php"

    - name: Check if Nginx conf file exists
      stat: path="/etc/nginx/sites-available/{{ http_conf }}"
      register: status

    - name: No need to reload Nginx
      debug: msg= {{ "No need to reload Nginx as sites-available entries have already been created" }}

    - name: Set Nginx conf file
      when: status.stat.exists == false
      template:
        src: "files/nginx.conf.j2"
        dest: "/etc/nginx/sites-available/{{ http_conf }}"

    - name: Enable new site
      when: status.stat.exists == false
      file:
        src: "/etc/nginx/sites-available/{{ http_conf }}"
        dest: "/etc/nginx/sites-enabled/{{ http_conf }}"
        state: link
      notify: Reload Nginx

  handlers:
    - name: Reload Nginx
      service:
        name: nginx
        state: reloaded