---
- name: Retrieve list of openshift nodes matching registry selector
  command: >
    {{ openshift.common.client_binary }} --api-version='v1' -o json
    get nodes -n default --config={{ openshift_hosted_kubeconfig }}
    --selector={{ openshift.hosted.registry.selector | default('') }}
  register: registry_nodes_json
  changed_when: false
  when: openshift.hosted.registry.replicas | default(none) is none

- set_fact:
    l_node_count: "{{ (registry_nodes_json.stdout | default('{\"items\":[]}') | from_json)['items'] | length }}"

# Determine the default number of registry/router replicas to use if no count
# has been specified.
# If no registry nodes defined, the default should be 0.
- set_fact:
    l_default_replicas: 0
  when: l_node_count | int == 0

# If registry nodes are defined and the registry storage kind is
# defined, default should be the number of registry nodes, otherwise
# just 1:
- set_fact:
    l_default_replicas: "{{ l_node_count if openshift.hosted.registry.storage.kind | default(none) is not none else 1 }}"
  when: l_node_count | int > 0

- set_fact:
    replicas: "{{ openshift.hosted.registry.replicas | default(l_default_replicas) }}"

- name: Create OpenShift registry
  command: >
    {{ openshift.common.client_binary }} adm registry --create
    --config={{ openshift_hosted_kubeconfig }}
    {% if replicas > 1 -%}
    --replicas={{ replicas }}
    {% endif -%}
    --namespace={{ openshift.hosted.registry.namespace | default('default') }}
    --service-account=registry
    {% if openshift.hosted.registry.selector | default(none) is not none -%}
    --selector='{{ openshift.hosted.registry.selector }}'
    {% endif -%}
    {% if not openshift.common.version_gte_3_2_or_1_2 | bool -%}
    --credentials={{ openshift_master_config_dir }}/openshift-registry.kubeconfig
    {% endif -%}
    {% if openshift.hosted.registry.registryurl | default(none) is not none -%}
    --images='{{ openshift.hosted.registry.registryurl }}'
    {% endif -%}
  register: openshift_hosted_registry_results
  changed_when: "'service exists' not in openshift_hosted_registry_results.stdout"
  failed_when: "openshift_hosted_registry_results.rc != 0 and 'service exists' not in openshift_hosted_registry_results.stdout and 'deployment_config' not in openshift_hosted_registry_results.stderr and 'service' not in openshift_hosted_registry_results.stderr"
  when: replicas | int > 0

- include: secure.yml
  static: no
  when: replicas | int > 0 and not (openshift.docker.hosted_registry_insecure | default(false) | bool)

- include: storage/object_storage.yml
  static: no
  when: replicas | int > 0 and openshift.hosted.registry.storage.kind | default(none) == 'object'

- include: storage/persistent_volume.yml
  static: no
  when: replicas | int > 0 and openshift.hosted.registry.storage.kind | default(none) in ['nfs', 'openstack']
