---
- name: Determine the timestamp for the backup.
  set_fact:
    now: '{{ lookup("pipe", "date +%F-%T") }}'

- 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' }}"

- 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: Create directory for backup
  file:
    state: directory
    path: "{{ playbook_dir }}/tower-openshift-backup-{{ now }}"

- name: Precreate file for database dump
  file:
    path: "{{ playbook_dir }}/tower-openshift-backup-{{ now }}/tower.db"
    state: touch
    mode: 0600

- name: Dump database
  shell: |
    {{ kubectl_or_oc }} -n {{ kubernetes_namespace }} exec ansible-tower-management -- \
      bash -c "PGPASSWORD={{ pg_password }} \
        pg_dump --clean --create \
          --host='{{ pg_hostname | default('postgresql') }}' \
          --port={{ pg_port | default('5432') }} \
          --username='{{ pg_username }}' \
          --dbname='{{ pg_database }}'" > {{ playbook_dir }}/tower-openshift-backup-{{ now }}/tower.db

- name: Copy inventory into backup directory
  copy:
    src: "{{ inventory_file }}"
    dest: "{{ playbook_dir }}/tower-openshift-backup-{{ now }}/"
    mode: 0600

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

- name: Create backup archive
  archive:
    path: "{{ playbook_dir }}/tower-openshift-backup-{{ now }}"
    dest: "{{ item }}"
  with_items:
    - "{{ playbook_dir }}/tower-openshift-backup-{{ now }}.tar.gz"
    - "{{ playbook_dir }}/tower-openshift-backup-latest.tar.gz"

- name: Remove temporary backup directory
  file:
    path: "{{ playbook_dir }}/tower-openshift-backup-{{ now }}"
    state: absent
