#!/bin/bash
#
# Download container images and upload them to local docker registry
set -euo pipefail

{% if upstream_container_images  %}
openstack overcloud container image prepare \
    --namespace tripleoupstream \
    --tag latest \
    --push-destination {{ ansible_br_ctlplane.ipv4.address }}:8787 \
    --images-file {{ container_images_location }}
source {{ undercloud_rc }}
openstack overcloud container image upload --verbose --config-file {{ container_images_location }}
{% else %}
REPO_FILE="$(find /etc/yum.repos.d/ -iname 'rhos-release-??.*')"
REPO_URL="$(grep -B2 enabled=1 $REPO_FILE | grep -m1 puddle | sed -E 's/.*(http.*[0-9]-RHEL-.\/).*/\1/')"
curl -L -o {{ working_dir }}/overcloud_container_image_prepare.yaml $REPO_URL/latest/overcloud_container_image_prepare.yaml
REGISTRY="$(grep -v ^# {{ working_dir }}/overcloud_container_image_prepare.yaml  | grep '  namespace' | awk -F': ' {'print $2'} | awk -F'/' {'print $1'})"
sudo sed -i -E "s/(--insecure-registry.*)\"/\1\ --insecure-registry\ $REGISTRY\"/" /etc/sysconfig/docker
sudo systemctl restart docker
TAG="$(openstack overcloud container image tag discover --image $REGISTRY/rhosp12/openstack-base:latest --tag-from-label version-release)"
{% if docker_registry_url != 'registry.example.local' %}
REGISTRY='{{ docker_registry_url }}'
{% endif %}
openstack overcloud container image prepare \
    --prefix=openstack- \
    --tag="$TAG" \
    --set ceph_image=rhceph-2-rhel7 \
    --set ceph_tag=latest \
    --push-destination {{ ansible_br_ctlplane.ipv4.address }}:8787 \
{% for envs in services.stdout_lines|default([]) %}
    --service-environment-file={{envs}} \
{% endfor %}
    --namespace=$REGISTRY/rhosp12 \
    --set ceph_namespace=$REGISTRY/ceph \
    --output-images-file {{ container_images_location }}

source {{ undercloud_rc }}
openstack overcloud container image upload --verbose --config-file {{ container_images_location }}
{% endif %}
