---
- name: Determine openssl version
  command: openssl version
  changed_when: false
  register: openssl

- name: Set mongosh package version
  set_fact:
    mongosh_package: "{{ 'mongodb-mongosh-shared-openssl3' if openssl.stdout.startswith('OpenSSL 3') else 'mongodb-mongosh-shared-openssl11' }}"
  when: mongosh_package is not defined

# tasks file for mongodb_install
- name: Install MongoDB Packages
  package:
    name:
      - "mongodb-org"
      - "mongodb-org-server"
      - "{{ mongosh_package }}"  # variablized due to tls issue
      - "mongodb-org-mongos"
      - "mongodb-org-tools"
    state: present
  when: specific_mongodb_version is not defined
  register: _pkg
  until: _pkg is succeeded
  retries: 5
  tags:
    - "mongodb"
    - "setup"
    - "pkg"

- name: Install MongoDB Packages (Specific version)
  package:
    name:
      - "mongodb-org-{{ specific_mongodb_version }}"
      - "mongodb-org-server-{{ specific_mongodb_version }}"
      - "{{ mongosh_package }}"  # variablized due to tls issue
      - "mongodb-org-mongos-{{ specific_mongodb_version }}"
      - "mongodb-org-tools-{{ specific_mongodb_version }}"
    state: present
  when:
    - specific_mongodb_version is defined
    - ansible_facts.os_family == "RedHat"
  register: _pkg
  until: _pkg is succeeded
  retries: 5
  tags:
    - "mongodb"
    - "setup"
    - "pkg"

# apt silliness:
# In order to upgrade/downgrade to a specific version of mongodb-org,
# we must also specify version of mongodb-org deps.
# https://dba.stackexchange.com/questions/197336/how-to-install-specific-mongo-version-from-the-ppa
- name: Install MongoDB Packages (Specific version)
  package:
    name:
      - "mongodb-org={{ specific_mongodb_version }}"
      - "mongodb-org-server={{ specific_mongodb_version }}"
      - "{{ mongosh_package }}"  # variablized due to tls issue
      - "mongodb-org-mongos={{ specific_mongodb_version }}"
      - "mongodb-org-tools={{ specific_mongodb_version }}"
    state: present
  when:
    - specific_mongodb_version is defined
    - ansible_facts.os_family == "Debian"
  register: _pkg
  until: _pkg is succeeded
  retries: 5
  tags:
    - "mongodb"
    - "setup"
    - "pkg"
    - "debian"

- name: Manage package locks - {{ mongodb_hold_packages }}
  script: lock_mongodb_packages.sh {{ mongodb_hold_packages }}
  when:
    - mongodb_hold_packages is defined
  tags:
    - "mongodb"
