# Copyright 2021 Dell Inc. or its subsidiaries. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
---
# tasks file for sm pod creation
- name: Get namespaces
  command: kubectl get namespaces
  changed_when: false
  register: k8s_namespaces
  tags: install

- name: Ensure that namespace is created
  command: kubectl create namespace subnet-manager
  when: "'subnet-manager' not in k8s_namespaces.stdout"
  tags: install

- name: Get K8s pods
  command: kubectl get pods --all-namespaces
  changed_when: false
  register: k8s_pods
  tags: install

- name: Create subnet manager pod
  block:
    - name: Replace container name in sm config file
      replace:
        path: "{{ sm_kube_config_file }}"
        regexp: "      containers:\n        - name:.*"
        replace: "      containers:\n        - name: {{ sm_container_name }}"
      tags: install

    - name: Replace image name in sm config file
      replace:
        path: "{{ sm_kube_config_file }}"
        regexp: "          image:.*"
        replace: "          image: 'localhost/{{ sm_docker_image_name }}:{{ sm_docker_image_tag }}'"
      tags: install

    - name: Replace cache directory in sm config file
      replace:
        path: "{{ sm_kube_config_file }}"
        regexp: "        - name: opensm-cache\n          hostPath:\n            path:.*"
        replace: "        - name: opensm-cache\n          hostPath:\n            path: {{ subnet_manager.cache_directory }} "
      tags: install

    - name: Replace cache directory in sm config file
      replace:
        path: "{{ sm_kube_config_file }}"
        regexp: "        - name: opensm-logs\n          hostPath:\n            path:.*"
        replace: "        - name: opensm-logs\n          hostPath:\n            path: {{ subnet_manager.log_directory }} "
      tags: install

    - name: Create subnet manager pod
      command: "kubectl apply -f {{ sm_kube_config_file }}"
      tags: install

  when: "'subnet-manager' not in k8s_pods.stdout"