---
# this will be useful later to understand if we're on vanilla k8s or OpenShift (OKD)
- name: "Get information about the cluster"
  set_fact:
    api_groups: "{{ lookup('k8s', cluster_info='api_groups') }}"

- name: Print some debug information
  vars:
    msg: |
      SmartGateway Variables
      --------------------------------------------
      {{ sg_vars | to_nice_yaml }}
  debug:
    msg: "{{ msg.split('\n') }}"

- name: Set Smart Gateway core image
  set_fact:
    core_container_image_path: "{{ lookup('env', 'RELATED_IMAGE_CORE_SMARTGATEWAY_IMAGE') | default('quay.io/infrawatch/sg-core:latest', true) }}"
  when: core_container_image_path is undefined

- name: Set Smart Gateway bridge image
  set_fact:
    bridge_container_image_path: "{{ lookup('env', 'RELATED_IMAGE_BRIDGE_SMARTGATEWAY_IMAGE') | default('quay.io/infrawatch/sg-bridge:latest', true) }}"
  when: bridge_container_image_path is undefined

- name: Check for existing cookie secret
  k8s_info:
    api_version: v1
    kind: Secret
    namespace: '{{ meta.namespace }}'
    name: 'smart-gateway-session-secret'
  register: session_secret

- name: Create cookie secret
  no_log: true
  k8s:
    definition:
      api_version: v1
      kind: Secret
      metadata:
        name: 'smart-gateway-session-secret'
        namespace: '{{ meta.namespace }}'
      stringData:
        session_secret: "{{ lookup('password', '/dev/null') }}"
  when: session_secret.resources|length == 0

# used as part of the Deployment object in order to trigger pod restarts on ConfigMap change
- name: Get Smart Gateway ConfigMap Environment
  set_fact:
    smartgateway_resource_configmap:
      env: "{{ lookup('template', item.name) | from_yaml }}"
  when: item.to_load | default(True)
  loop:
    - name: sg-core-configmap.yaml.j2

- name: Deploy Smart Gateway
  k8s:
    state: "{{ state }}"
    definition: "{{ lookup('template', item.name) | from_yaml }}"
  when: item.to_load | default(True)
  loop:
    - name: sg-core-configmap.yaml.j2
    - name: deployment.yaml.j2

- name: Deploy services requested by this Smart Gateway
  include_tasks: base_service.yml
  loop: "{{ services }}"
  loop_control:
    loop_var: this_service
  when:
    - services is defined
