---
- name: Create local temp dir for OpenShift hosted templates copy
  local_action: command mktemp -d /tmp/openshift-ansible-XXXXXXX
  become: False
  register: copy_hosted_templates_mktemp
  run_once: True

- name: Create tar of OpenShift examples
  local_action: command tar -C "{{ role_path }}/files/{{ content_version }}/{{ hosted_deployment_type }}" -cvf "{{ copy_hosted_templates_mktemp.stdout }}/openshift-hosted-templates.tar" .
  args:
    # Disables the following warning:
    # Consider using unarchive module rather than running tar
    warn: no
  become: False
  register: copy_hosted_templates_tar

- name: Create remote OpenShift hosted templates directory
  file:
    dest: "{{ hosted_base }}"
    state: directory
    mode: 0755

- name: Unarchive the OpenShift hosted templates on the remote
  unarchive:
    src: "{{ copy_hosted_templates_mktemp.stdout }}/openshift-hosted-templates.tar"
    dest: "{{ hosted_base }}/"

- name: Cleanup the OpenShift hosted templates temp dir
  become: False
  local_action: file dest="{{ copy_hosted_templates_mktemp.stdout }}" state=absent

- name: Modify registry paths if registry_url is not registry.access.redhat.com
  shell: >
    find {{ hosted_base }} -type f | xargs -n 1 sed -i 's|registry.access.redhat.com|{{ registry_host | quote }}|g'
  when: registry_host != '' and openshift_hosted_modify_imagestreams | default(False) | bool

- name: Create temp directory for kubeconfig
  command: mktemp -d /tmp/openshift-ansible-XXXXXX
  register: mktemp
  changed_when: False

- name: Record kubeconfig tmp dir
  set_fact:
    openshift_hosted_templates_kubeconfig: "{{ mktemp.stdout }}/admin.kubeconfig"

- name: Copy the admin client config(s)
  command: >
    cp {{ openshift.common.config_base }}/master/admin.kubeconfig {{ openshift_hosted_templates_kubeconfig }}
  changed_when: False

- name: Create or update hosted templates
  command: >
    {{ openshift.common.client_binary }} {{ openshift_hosted_templates_import_command }}
    -f {{ hosted_base }}
    --config={{ openshift_hosted_templates_kubeconfig }}
    -n openshift
  register: oht_import_templates
  failed_when: "'already exists' not in oht_import_templates.stderr and oht_import_templates.rc != 0"
  changed_when: "'created' in oht_import_templates.stdout"

- name: Delete temp directory
  file:
    name: "{{ mktemp.stdout }}"
    state: absent
  changed_when: False
