---
- include_tasks: openshift_auth.yml
  when: openshift_host is defined

- include_tasks: kubernetes_auth.yml
  when: kubernetes_context is defined

- name: Use kubectl or oc
  set_fact:
    kubectl_or_oc: "{{ openshift_oc_bin if openshift_oc_bin is defined else 'kubectl' }}"

- set_fact:
    deployment_object: "deployment"

- name: Record deployment size
  shell: |
    {{ kubectl_or_oc }} -n {{ kubernetes_namespace }} \
      get {{ deployment_object }} {{ kubernetes_deployment_name }} -o jsonpath="{.status.replicas}"
  register: deployment_size

- name: Scale deployment down
  shell: |
    {{ kubectl_or_oc }} -n {{ kubernetes_namespace }} \
      scale {{ deployment_object }} {{ kubernetes_deployment_name }} --replicas=0

- name: Wait for scale down
  shell: |
    {{ kubectl_or_oc }} -n {{ kubernetes_namespace }} get pods \
      -o jsonpath='{.items[*].metadata.name}' \
      | tr -s '[[:space:]]' '\n' \
      | grep {{ kubernetes_deployment_name }} \
      | grep -v postgres | wc -l
  register: tower_pods
  until: (tower_pods.stdout | trim) == '0'
  retries: 30

- name: Delete any existing management pod
  shell: |
    {{ kubectl_or_oc }} -n {{ kubernetes_namespace }} \
      delete pod ansible-tower-management --grace-period=0 --ignore-not-found

- name: Template management pod
  set_fact:
    management_pod: "{{ lookup('template', 'management-pod.yml.j2') }}"

- name: Create management pod
  shell: |
    echo {{ management_pod | quote }} | {{ kubectl_or_oc }} apply -f -

- name: Wait for management pod to start
  shell: |
    {{ kubectl_or_oc }} -n {{ kubernetes_namespace }} \
      get pod ansible-tower-management -o jsonpath="{.status.phase}"
  register: result
  until: result.stdout == "Running"
  retries: 60
  delay: 10

- name: generate a new SECRET_KEY
  shell: |
    {{ kubectl_or_oc }} -n {{ kubernetes_namespace }} \
      exec -i ansible-tower-management -- bash -c "awx-manage regenerate_secret_key"
  register: new_key

- name: print the new SECRET_KEY
  debug:
    msg: "{{ new_key.stdout }}"

- name: Delete management pod
  shell: |
    {{ kubectl_or_oc }} -n {{ kubernetes_namespace }} \
      delete pod ansible-tower-management --grace-period=0 --ignore-not-found
