#!/bin/bash

set -eux

IMG_SOURCE_URL=${IMG_SOURCE_URL:-"http://repos.fedorapeople.org/repos/openstack-m/tripleo-images-rdo-icehouse"}

OS_AUTH_URL=${OS_AUTH_URL:-""}
if [ -z "$OS_AUTH_URL" ]; then
    echo "You must source a stackrc file for the Undercloud."
    exit 1
fi

# generate ssh authentication keys if they don't exist
if [ ! -f ~/.ssh/id_rsa ]; then
  ssh-keygen -t rsa -N ""  -f ~/.ssh/id_rsa
fi

if ! nova keypair-show default 2>&1 1>/dev/null; then
	tripleo user-config
fi

function download_image {
    local image_name=$1

    if [ ! -f $image_name ]; then
        curl -L -O $IMG_SOURCE_URL/$image_name
    fi
}

function load_image {
    local image_name=$1

    tripleo load-image -d $image_name
}

download_image deploy-ramdisk.initramfs
download_image deploy-ramdisk.kernel
download_image overcloud-control.qcow2
download_image overcloud-compute.qcow2
download_image overcloud-cinder-volume.qcow2
download_image overcloud-swift-storage.qcow2
download_image fedora-user.qcow2

load_image overcloud-control.qcow2
load_image overcloud-compute.qcow2
load_image overcloud-cinder-volume.qcow2
load_image overcloud-swift-storage.qcow2

glance image-delete bm-deploy-kernel 2>/dev/null || :
glance image-create --name bm-deploy-kernel --public \
    --disk-format aki < deploy-ramdisk.kernel
glance image-delete bm-deploy-ramdisk 2>/dev/null || :
glance image-create --name bm-deploy-ramdisk --public \
    --disk-format ari < deploy-ramdisk.initramfs
