#!/bin/bash

#   Config


RCFILE=$1


XENIAL_IMAGE_NAME="Ubuntu 16.04 - GARR"
TRUSTY_IMAGE_NAME="Ubuntu 14.04 - GARR"

if [ ! -e $RCFILE ]
then
        echo "RC file not found! $RCFILE"
        exit 1

fi

source $RCFILE

export ADMIN_USER_DOMAIN_NAME=$OS_USER_DOMAIN_NAME
export ADMIN_PROJECT_ID=$OS_PROJECT_ID
export ADMIN_PROJECT_NAME=$OS_PROJECT_NAME
export ADMIN_DOMAIN_NAME=$OS_DOMAIN_NAME
export ADMIN_IDENTITY_API_VERSION=3
export ADMIN_AUTH_VERSION=$OS_AUTH_VERSION

export ADMIN_USERNAME=$OS_USERNAME
export ADMIN_AUTH_URL=$OS_AUTH_URL
export ADMIN_PASSWORD=$OS_PASSWORD

export ADMIN_REGION_NAME=$OS_REGION_NAME

export KEY_PATH="~/.ssh/id_progress.pub"

export ADMIN_TENANT_NAME=admin

unset OS_PROJECT_ID
unset OS_REGION_NAME
unset OS_USER_DOMAIN_NAME
unset OS_PROJECT_NAME
unset OS_AUTH_VERSION
unset OS_IDENTITY_API_VERSION
unset OS_PASSWORD
unset OS_AUTH_URL
unset OS_USERNAME
unset OS_PROJECT_DOMAIN_NAME

export AUTH_v3="--os-identity-api-version=3 --os-project-id=$ADMIN_PROJECT_ID --os-username=$ADMIN_USERNAME --os-user-domain-name=$ADMIN_USER_DOMAIN_NAME --os-password=$ADMIN_PASSWORD --os-region-name=$ADMIN_REGION_NAME --os-project-name=$ADMIN_PROJECT_NAME --os-domain-name=$ADMIN_DOMAIN_NAME --os-auth-url=$ADMIN_AUTH_URL"

mkdir -p ~/simplestreams

IMAGE_ID=$(openstack $AUTH_v3 image list | grep "$XENIAL_IMAGE_NAME"| awk '{print $2}')

echo "IMAGE $XENIAL_IMAGE_NAME SERIES xenial ID $IMAGE_ID"

juju metadata generate-image -d ~/simplestreams -i $IMAGE_ID -s xenial -r $ADMIN_REGION_NAME -u $ADMIN_AUTH_URL

IMAGE_ID=$(openstack $AUTH_v3 image list | grep "$TRUSTY_IMAGE_NAME"| awk '{print $2}')

echo "IMAGE $TRUSTY_IMAGE_NAME SERIES trusty ID $IMAGE_ID"

juju metadata generate-image -d ~/simplestreams -i $IMAGE_ID -s trusty -r $ADMIN_REGION_NAME -u $ADMIN_AUTH_URL

cd ~/simplestreams

echo "Metadata content:"

cat images/streams/v1/com.ubuntu.cloud-released-imagemetadata.json 

swift $AUTH_v3 upload simplestreams *

swift $AUTH_v3 post simplestreams --read-acl .r:*

