# Copyright BigchainDB GmbH and BigchainDB contributors
# SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
# Code is Apache-2.0 and docs are CC-BY-4.0

---
- name: Running MongoDB Docker
  docker_container:
    name: "{{ mongodb_docker_name }}{{ item }}"
    hostname: "{{ mongodb_docker_name }}{{ item }}"
    image: "mongo:{{ mongo_version }}"
    detach: true
    network_mode: bridge
    networks:
      - name: "{{ bigchaindb_docker_net }}"
    published_ports:
      - "{{ mongodb_port }}"
    restart_policy: unless-stopped
    volumes:
      - "{{ mongodb_host_mount_dir }}{{ item|string }}/db:{{ mongodb_storage_path }}"
      - "{{ mongodb_host_mount_dir }}{{ item|string }}/configdb:{{ mongodb_config_path }}"
    state: started
    keep_volumes: true
    command: mongod
  with_sequence: start=1 end="{{ stack_size|int }}" stride=1
  when: stack_type|lower == "docker" or stack_type|lower == "cloud"
  tags: [mongodb]

- name: Creating directories
  file:
    path: "{{ item }}"
    state: directory
    mode: 0700
  with_items: "{{ directories }}"
  when: stack_type|lower == "local"
  tags: [mongodb]

- import_tasks: debian.yml
  when: stack_type|lower == "local" and (distribution_name == "debian" or distribution_name == "ubuntu")
  tags: [mongodb]

- import_tasks: centos.yml
  when: stack_type|lower == "local" and (distribution_name == "centos" or distribution_name == "red hat enterprise linux")
  tags: [mongodb]

- import_tasks: fedora.yml
  when: stack_type|lower == "local" and (distribution_name == "fedora")
  tags: [mongodb]

- name: MongoDB Process Check
  shell: pgrep mongod | wc -l
  register: command_result
  when: stack_type|lower == "local"
  tags: [mongodb]

- name: Run MongoDB
  shell: nohup mongod > /tmp/mongodb_log_$(date +%Y%m%d_%H%M%S) 2>&1 &
  register: start_mdb
  failed_when: "'FAILED' in start_mdb.stderr or start_mdb.rc != 0"
  when: stack_type|lower == "local" and command_result.stdout| int == 0
  tags: [mongodb]